How is the behavior of if- and if if different? expression affects range operator in scalar context?

On http://novosial.org/perl/one-liner/ I found the following two single-line. The outputs are different because the operator unlessis different from if !(due to the rules of associativity and priority).

cat file:  
foo  



bar  
perl -ne 'print unless /^$/../^$/' file  
foo  
bar  
perl -ne 'print if! /^$/../^$/ 'file  
foo  

bar  

How does the different if !-statement behavior make the second single-line output one empty line?

+3
source share
3 answers

As the related article says, this is a matter of associativity and priority ...

print unless /^$/../^$/ print if !(/^$/../^$/)

print if ! /^$/../^$/ print if (!/^$/)../^$/

, , , .

+6

, IMHO, , Perl if !: if !. ! if; . , .

,

do_something() unless something;

do_something() if something-else;

:

do_something() unless ( something );

do_something() if ( something-else );

something-else , something, , ! .

not.

perl -ne 'print if not /^$/../^$/' file  

. not perldoc perlop:

Unary not . !, .

+4

The range test will return true until the 2nd operand is correct. Then it will return false on the next call.

This snippet will tell us what the range operator returns.

perl -ne "$x= ( ! /^$/../^$/ ) ; print qq/$x : $_/" range_test.TXT

which produces

1 : foo
2E0 :
 :
 :
1 : bar

So, the first empty line generates a true answer, the next false

+1
source

Source: https://habr.com/ru/post/1735772/


All Articles