0

Can anyone explain the difference in output of the two perl (using cygwin) commands below:

$ echo abc | perl -n -e 'if ($_ =~ /a/) {print 1;}'

prints :

1

$ echo abc | perl -e 'if ($_ =~ /a/) {print 1;}'

The first prints '1' while second one outputs blank?

Thanks

1 Answer 1

1

-n switch adds while loop around your code, so in your case $_ is populated from standard input. In second example there is no while loop thus $_ is leaved undefined.

Using Deparse you can ask perl to show how your code is parsed,

perl -MO=Deparse -n -e 'if ($_ =~ /a/) {print 1;}'

LINE: while (defined($_ = <ARGV>)) {
    if ($_ =~ /a/) {
        print 1;
    }
}

perl -MO=Deparse -e 'if ($_ =~ /a/) {print 1;}'

if ($_ =~ /a/) {
    print 1;
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, that explains. Now I have question regarding use of perl command line option -MO=Deparse you have used. According to Perl --help this option means -[mM][-]module execute "use/no module..." before executing program. My question is, how do you know about the O and = characters in this option (-MO=Deparse). Is it documented?
@Rajeev yes, -M does that.
@Rajeev O is the module name, and Deparse is the function that is requested to be imported. An alternative option would be -MList::Util=sum, which would important the sum function of List::Util

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.