Why can't you assign a value in ternary operation?

Lecar_red on 2008-07-28T18:01:02

I'm sure there is a good reason why this works the way it does.

If I set a local variable inside a ternary operator like:

print ( my $foo = bar() ? $foo : "unknown" ) 

It works very closely to my expectations (which I'm sure are off). If bar returns any flavor of false, it will print the "unknown" value. And if bar return true it will call the correct part of the operation. But the local variable assignment will not be set so the output will be an empty string.

Anyone know why? Is this a scope thing?

P.S. Yes, I know there are other ways to do this with string printing. In my real world case, I have a much more delicate assignment and would like to cleanly assign and evaluate in one line. Plus I'm curious :)


Are you running this…

phaylon on 2008-07-28T18:52:19

…with strict and warnings enabled?

Two different vars

brian_d_foy on 2008-07-28T19:39:00

You have two different $foo variables in there. Is that the actual code you're trying to use?

If the package version of $foo has a value, that's what the lexical version of $foo gets in the assignment:

$foo = 'Hello'; # package version
 
print(  my $foo = bar() ? $foo : "unknown" );
 
print "foo is [$foo]";
 
sub bar { 1 };

Re:Two different vars

Lecar_red on 2008-07-28T20:38:23

Ah... now I see.

My brain really wants the parens to be a block...

Thanks