What is the result of Perl's &&?

前端 未结 3 1055
野趣味
野趣味 2021-01-18 12:29

When I try this:

$a = 1;
$b = 2;
print ($a && $b) . \"\\n\";

The result is 2. Why?

3条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-18 13:02

    That's how the && operator works: if the left-hand argument evaluates as true, the value of the expression is that of the value of the right-hand argument. This is covered on the perlop page.

    However, you've also let yourself open to a much more subtle problem. You'll find that the newline doesn't get printed. This is because if you put an expression in brackets after print (or any other function name) the arguments passed to print are just those in the brackets. To get notice of this, make sure you switch on warnings. Put these lines at the top of each program:

    #!/usr/bin/perl -w
    
    use strict;
    

    until you understand them enough to decide for yourself whether to continue with them. :-)

    In your case, you'll get this:

    print (...) interpreted as function at p line 7.
    Useless use of concatenation (.) or string in void context at p line 7.
    

提交回复
热议问题