Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Please explain the '$x ||' idiom

by goonfest (Sexton)
on Jan 18, 2005 at 17:33 UTC ( [id://423104]=perlquestion: print w/replies, xml ) Need Help??

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"

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://423104]
Approved by amw1
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chanting in the Monastery: (8)
As of 2024-04-23 10:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found