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

后端 未结 3 861
一向
一向 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:39

    You use single quotes in one-liners to protect your Perl code from being evaluated by the shell. In this command:

    perl -ne 'chomp; print "'$_'\n"' shortlist.txt
    

    you close the single quotes before $_, so the shell expands $_ to the last argument to the previous command. In your case, this happened to be the name of your input file, but the output would be different if you ran a different command first:

    $ echo foo
    $ perl -ne 'chomp; print "'$_'\n"' shortlist.txt
    foo
    foo
    foo
    foo
    foo
    

提交回复
热议问题