Odd Behavior of Perl Conditional Operator

I am doing some work in Perl, and I came across an odd result with a conditional statement.

The code in question:

($foo eq "blah") ? @x = @somearray : @y = ("another","array");

Attempting to compile this code results in an error " Assignment to both a list and a scalar at XXX line YY, near ');'". Trying to determine the source of the error, I wrote this using a couple of different ways to represent the array in Perl, and they all return with the same error. Now at first I thought it was just some kind of stupid explicit mistake with assignment statements, but to satisfy my curiosity, I rewrote the expression in more detail:

if($foo eq "blah") {
    @x = @somearray;
} else {
    @y = ("another","array");
}

This version of the code compiled perfectly.

- , if-else, ? . , Perl , ?

+3
5
$ perl -MO=Deparse -e'($foo eq "blah") ? @x = @somearray : @y = ("another","array");'
Assignment to both a list and a scalar at -e line 1, near ");"
-e had compilation errors.
$foo eq 'blah' ? (@x = @somearray) : @y = ('another', 'array');
$ perl -MO=Deparse -e'($foo eq "blah") ? @x = @somearray : (@y = ("another","array"));'
$foo eq 'blah' ? (@x = @somearray) : (@y = ('another', 'array'));
-e syntax OK

: ?: , =.

+15

Perl

$variable = ()? : ;

, , , , if/else. , .

+9

perlop , .

- , . !

+7

, , Perl , :

$x = ($foo eq "blah") ? $somevalue : ("another","array");

, $x 2 ( ).

, , :

# this is wrong, for the same order-of-operations reasons as with arrays
($foo eq "blah") ? $x = $somevalue : $x = "another value";

( ) :

$x = ($foo eq "blah") ? $somevalue : "another value";

, :

@x = ($foo eq "blah") ? @somearray : ("another","array");
+6

"" "".

$foo eq 'blah' and @x = @somearray or @y = ('another', 'array');

, @x = @somearray true. .

+2
source

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


All Articles