Slash Boxes
NOTE: use Perl; is on undef hiatus. You can read content, but you can't post it. More info will be forthcoming forthcomingly.

All the Perl that's Practical to Extract and Report

use Perl Log In

Log In

[ Create a new account ]

Lecar_red (5694)

  (email not shown publicly)

Journal of Lecar_red (5694)

Monday July 28, 2008
01:01 PM

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

[ #37031 ]

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 :)

The Fine Print: The following comments are owned by whoever posted them. We are not responsible for them in any way.
More | Login | Reply
Loading... please wait.
  • …with strict and warnings enabled?
    Ordinary morality is for ordinary people. -- Aleister Crowley
  • 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 };