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

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

    I try to avoid quotes in one liners for just this reason. I use generalized quoting when I can:

    % perl -ne 'chomp; print qq($_\n)'
    

    Although I can avoid even that with the -l switch to get the newline for free:

    % perl -nle 'chomp; print $_'
    

    If I don't understand a one-liner, I use -MO=Deparse to see what Perl thinks it is. The first two are what you expect:

    % perl -MO=Deparse -ne 'chomp; print "$_\n"' shortlist.txt
    LINE: while (defined($_ = )) {
        chomp $_;
        print "$_\n";
    }
    -e syntax OK
    
    % perl -MO=Deparse -ne 'chomp; print "$ARGV\n"' shortlist.txt
    LINE: while (defined($_ = )) {
        chomp $_;
        print "$ARGV\n";
    }
    -e syntax OK
    

    You see something funny in the one where you saw the problem. The variable has disappeared before perl ever saw it and there's a constant string in its place:

    % perl -MO=Deparse -ne 'chomp; print "'$_'\n"' shortlist.txt
    
    LINE: while (defined($_ = )) {
        chomp $_;
        print "shortlist.txt\n";
    }
    -e syntax OK
    

    Your fix is curious too because Deparse puts the variable name in braces to separate it from the old package specifier ':

    % perl -MO=Deparse -ne 'chomp; print "'\''$_'\''\n"' shortlist.txt
    LINE: while (defined($_ = )) {
        chomp $_;
        print "'${_}'\n";
    }
    -e syntax OK
    

提交回复
热议问题