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

What does the following line of code do? I've never seen it before but am now debugging somebody else's program that has this. Thanks.

$x = $x ||5;

"Be proud, be a Goon"

Retitled by davido.

Replies are listed 'Best First'.
Re: Please explain the '$x ||' idiom
by Tanktalus (Canon) on Jan 18, 2005 at 17:35 UTC

    $x is set to $x, unless $x is false, in which case it's set to 5. Same as $x ||= 5. Check perlop for more info.

Re: Please explain the '$x ||' idiom
by amw1 (Friar) on Jan 18, 2005 at 17:36 UTC
    Basically this reads set $x to 5 if $x is false (0 or undef)
    $x = 0; $x = $x || 5; # prints 5 print $x; $x = 4; $x = $x || 5; $prints 4 print $x; $x = $x || 5; # prints 5 print $x;
      . . . $x is false (0 or undef)

      0 (but not "0 but true"), undef, or the empty string ""</nit>

Re: Please explain the '$x ||' idiom
by goonfest (Sexton) on Jan 18, 2005 at 17:45 UTC
    Okay. Thanks dudes!

    "Be proud, be a Goon"