Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re: Or, Or, Equals Zero, $x ||= 0

by graff (Chancellor)
on Nov 28, 2007 at 02:09 UTC ( [id://653450]=note: print w/replies, xml ) Need Help??


in reply to Or, Or, Equals Zero, $x ||= 0

The reason for using that expression is probably that the original script author was (wisely) including a "-w" flag on the shebang line, or put "use warnings;" near the top of the script. In those cases, the  $x ||= 0; will prevent perl from issuing a warning about "use of undefined value in numeric comparison" or "use of undefined value in print".

Works for strings too:  $x ||= '': will avoid warnings about using an undefined value in a print, string concatenation, string comparison, regular expression, and so on.

It's not that undefined values are inherently bad -- sometimes you want a variable to be undef, and if you really want to use undef values in a print or a comparison to some actual value, you can modify the "use warnings" pragma to say which warnings it should ignore. But such "special needs" cases are pretty rare (and probably avoidable).

Replies are listed 'Best First'.
Re^2: Or, Or, Equals Zero, $x ||= 0 ('')
by tye (Sage) on Nov 28, 2007 at 05:56 UTC
    Works for strings too: $x ||= '': will avoid warnings about using an undefined value in a print, string concatenation, string comparison, regular expression, and so on.

    That also turns '0' into '' and so would probably be better written as:

    $x= '' if ! defined $x;

    Or you can use //= if you are on the bleading edge and eschew backward compatability. Note that ||= is probably the best choice for the numeric case as treating '' as a number can also cause a warning.

    - tye        

      If it's on a new code, and no animals are harmed, I don't see a problem with using 5.10 syntax. It's a question of what the people around you like to read. For instance, I'd write it
      $x= '' unless defined $x;
      But its a question of whatever suits.

      Software speaks in tongues of man; I debug, therefore I code.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (5)
As of 2024-04-19 09:49 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found