in reply to creating a variable in an if statement

perl -wMstrict -e "sub S1 { return int rand 2 ? ('one 1') : () } sub S2 { return int rand 2 ? ('one 2') : ('bad', 'news') } for (0 .. shift) { if (1 == (my @f = S1 || S2)) { print @f } else { print 'not one' } print qq(\n); }" 10 one 1 one 1 one 1 not one one 2 not one one 2 one 1 not one one 1 not one

Replies are listed 'Best First'.
Re^2: creating a variable in an if statement
by shmem (Chancellor) on Jan 22, 2008 at 21:34 UTC
    That's flawed since in
    if (1 == (my @f = S1 || S2)) {

    scalar context is forced upon the return of S1, but not on that of S2:

    perl -le '@g = qw(a b c); @h = qw(d e); @f = @g || @h; print @f' 3 perl -le '@g = qw( ); @h = qw(d e); @f = @g || @h; print @f' de

    What if S1 returns more than one element?

    --shmem

    _($_=" "x(1<<5)."?\n".q·/)Oo.  G°\        /
                                  /\_¯/(q    /
    ----------------------------  \__(m.====·.(_("always off the crowd"))."·
    ");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}
Re^2: creating a variable in an if statement
by ikegami (Patriarch) on Jan 22, 2008 at 21:36 UTC

    In the OP's code,

    sub S1 { return qw( a b ); } sub S2 { return qw( c ); }

    S2 would get called and the result would be @f=qw(c). But with yours, S2 doesn't get called and the result is @f=qw(b).