Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Is there any danger in doing something like this?

$temp = defined($temp = &func()) ? $temp : 'undefined';
When I say 'danger', I'm wondering if I may be surprised at my result due to the order of evaluation being different than I expect.

By the way, my motivation for this is to either save a little space by not declaring an extra variable:

$temp1 = &func(); $temp2 = defined($temp1) ? $temp1 : 'undefined';
or to save a little time by not calling func twice:
$temp = defined(&func()) ? $func() : 'undefined';

Replies are listed 'Best First'.
Re: Safe to use ternary operator like this?
by ChOas (Curate) on Nov 16, 2000 at 20:13 UTC
    I have to run, but I just saw this...
    this is how I would do it:
    my $Temp=&Func() || 'undefined';

    Bye!!

      This will set $Temp to 'undefined' if &Func returns a false value (see What is true and false in Perl? for more details). I like the original code, methinks. It's just what the ternary operator was designed to do.

      Philosophy can be made out of anything. Or less -- Jerry A. Fodor

      Not quite the same thing depending on the sub return though:
      use strict; my $temp; $temp = defined ($temp = func()) ? $temp : 'undefined'; print "func:$temp\n"; $temp = func() || 'undefined'; print "func:$temp\n"; sub func { return ''; }
      produces:
      func: func:undefined