Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

perl :"//" operator?

Tags:

I have a question about using "//" operator, my testing code is as following:

perl -e '@arr1=();@arr2=(1,2,3);@arr3=defined(@arr1)?@arr1:@arr2;print "[@arr3]\n"'   [1 2 3]   perl -e '@arr1=();@arr2=(1,2,3);@arr3=@arr1//@arr2;print "[@arr3]\n"'   [0]   perl -e '$v1=();$v2="123";$v3=defined($v1)?$v1:$v2;print "[$v3]\n"'   [123]   perl -e '$v1=();$v2="123";$v3=$v1//$v2;print "[$v3]\n"'   [123] 

my question is, why do using "//" operator give the same results as using "defined()? : " on the scalar, but not array(or hash)?

Thanks!!!

like image 972
ss-perl Avatar asked Sep 13 '11 22:09

ss-perl


People also ask

What does == mean in Perl?

== (equal to)Checks if the value of two operands are equal or not, if yes then condition becomes true. Example − ($a == $b) is not true.


1 Answers

Because the leftmost operand of ?:, ||, or && — or this newfanglulated // thingie — is always evaluated in boolean not list context, whereas the other operands inherit the surrounding context.

@a = @b && @c; 

means

if (@b) {      @a = @c; } else {      @a = scalar @b; } 

While

@a = @b || @c; 

and also

@a = @b // @c; 

both mean

means

if (@b) {      @a = scalar @b; } else {      @a = @c; } 

The only way to get rid of the scalar in assigning @b to @a is to use ?:

@a = @b ? @b : @c; 

which of course means

if (@b) {     @a = @b; } else {     @a = @c; } 

There is also the property that ?: can be an lvalue:

(@a > @b ? @a : @b) = @c; 

which of course means

if (@a > @b) {     @a = @c; } else {     @b = @c; } 

EDIT

The implementation of @a // @b and its definition differ. Bug submitted. Thanks.

like image 171
tchrist Avatar answered Oct 02 '22 21:10

tchrist