Why is '$_' the same as $ARGV in a Perl one-liner?

后端 未结 3 828
一向
一向 2021-01-21 08:15

I ran into this problem while trying to print single quotes in a Perl one-liner. I eventually figured out you have to escape them with \'\\\'\'. Here\'s some code t

3条回答
  •  时光取名叫无心
    2021-01-21 08:52

    To your shell, 'chomp; print "'$_'\n"' results in a string that's the concatenation of

    1. chomp; print " (the first sequence inside single quotes),
    2. the value of its variable $_, and
    3. \n" (the second sequence inside single quotes).

    In bash, $_ "... expands to the last argument to the previous command, after expansion. ...". Since this happens to be shortlist.txt, the following is passed to perl:

    chomp; print "shortlist.txt\n"
    

    For example,

    $ echo foo
    foo
    
    $ echo 'chomp; print "'$_'\n"'
    chomp; print "foo\n"
    

    Note that the above mechanism shouldn't be used to pass values to a Perl one-liner. You shouldn't be generating Perl code from the shell. See How can I process options using Perl in -n or -p mode? for how to provide arguments to a one-liner.

提交回复
热议问题