Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

"or die" versus "|| die"

by ghenry (Vicar)
on Jun 24, 2005 at 14:48 UTC ( #469724=perlquestion: print w/ replies, xml ) Need Help??
ghenry has asked for the wisdom of the Perl Monks concerning the following question:

Update: I asked this in the CB, but wanted to keep a record of it here for other inexperienced Monks like myself.

In Downloading a lot of files yesterday, I did the classic or die whilst opening a file, as per most code I've ever seen.

However, in the perlfaq, How can I read in an entire file all at once? I see a lot of || die

In Downloading a lot of files, I use:

open( RPMS, "<", "./upgrade.log" ) or die "can't open file: $!\n";

but in perlopentut - Simple Opens it shows

open( INFO, ">", $datafile ) || die "Can't create $datafile: $!";

Which way is the best and why?

Thanks,
Gavin.

Walking the road to enlightenment... I found a penguin and a camel on the way.....
Fancy a yourname@perl.me.uk? Just ask!!!

Comment on "or die" versus "|| die"
Select or Download Code
Re: "or die" versus "|| die"
by jeffa (Chancellor) on Jun 24, 2005 at 14:56 UTC

    In your example it doesn't matter. One binds more tightly than the other, is the only real difference -- well, that and readablilty. || binds tighter. So, if you want to die after an assignment use or:

    my $foo = $bar->fetch('baz') or die "something went wrong\n";
    And if you want a default value, use ||
    my $foo = $bar->fetch('baz') || 'default';

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    B--B--B--B--B--B--B--B--
    H---H---H---H---H---H---
    (the triplet paradiddle with high-hat)
    
Re: "or die" versus "|| die"
by kyoshu (Curate) on Jun 24, 2005 at 14:58 UTC
    there is no difference as far as i know, you can change 'or' with '||' and you can change 'and' with "&&".

    20050625 Edit by ysth: restore content

      No they cannot be used interchangeably in all places, the word versions are specifically guaranteed to have lower precedence than the symbol versions (infact guaranteed to have the lowest precedence of any operators), you might care to try for instance:

      open ONE, "somefilethatdoesnexist" or print "one: $!\n"; open TWO, "somefilethatdoesnexist" || print "two: $!\n";
      As you can see the latter doesn't behave as expected as the '||' binds more tightly and ends up taking the value of the filename - infact the check is optimised away because this is essentially a no-op, as the output from B::Deparse shows:
      print "one: $!\n" unless open ONE, 'somefilethatdoesnexist'; open TWO, 'somefilethatdoesnexist';

      /J\

      Jeffa's response shows the difference -- because of the way those ops are weighted for ordering, depending on what statements you use them in, they end up meaning different things. In the source that is shown as on the OP's example there is no difference in execution -- but that can't be said in a blanket statement.


      -Waswas

        Beware of violating your own sig.

        For a very thorough explaination of just what the differences are between the two (just an issue with precedence, which has already been covered), and the order of precedence for all perl operators, see the perldoc perlop

      They mean the same thing semantically, but they are not interchangable. The difference is precedence. See perlop.

      thor

      Feel the white light, the light within
      Be your own disciple, fan the sparks of will
      For all of us waiting, your kingdom will come

      Yes these is a difference, as jeffa pointed out: precedence. As long as you use parentheses around e.d. open, it doesn't matter, but else it really makes a difference if you say:
      open F, $file or die;
      which will die when the open failes, or:
      open F, $file || die
      which will die if $file is false (undef, empty or 0), but NOT if the open fails!

      Paul

      kyoshu, please don't delete your posts this way. It makes the following answers look out-of-context, and deny the possibility to learn to the other readers. Many times one learns from errors, even others' ones.

      It's better to put a pen strike over the sentences you don't agree any more like this, which can be obtained via the strike tag:

      <strike>like this</strike>
      And yes, if you'll ever restore the original content... this post will look out-of-context!

      Flavio
      perl -ple'$_=reverse' <<<ti.xittelop@oivalf

      Don't fool yourself.
Re: "or die" versus "|| die"
by davidrw (Prior) on Jun 24, 2005 at 15:02 UTC
    I think in a lot of cases it doesn't matter (especially if die'ing), but there is a difference in precedence. perldoc perlop shows that || is higher than = and some other operators, and or has the lowest pecedence.

    I've had cases where || return needed to be changed to or return so that Devel::Cover wouldn't complain about never getting a true value for the other half of the construct.

      Just because you're invoking die after an || or a or doesn't mean you don't have to think about precedence. Consider the following:

      somesub $this, $that || die;

      If you use 'or' here, you'll die upon failure of somesub (assuming it returns false to indicate failure). If you use ||, you'll die if $that is false. Big difference.


      Dave

        Just because you're invoking die after an || or a or doesn't mean you don't have to think about precedence. Consider the following: somesub $this, $that || die; If you use 'or' here, you'll die upon failure of somesub (assuming it returns false to indicate failure). If you use ||, you'll die if $that is false. Big difference.

        If you call somesub with parens, the argument list is clearer to novice coders, the notation matches what they learned in grade 6 math class, and in this case, the precedence issue disappears.

        In my experience, thinking too hard about precedence is usually a clue that you're being too tricky with your code.

Re: "or die" versus "|| die"
by trammell (Priest) on Jun 24, 2005 at 15:17 UTC
Re: "or die" versus "|| die"
by ysth (Canon) on Jun 24, 2005 at 15:33 UTC

      Which error? The numeric comparison operator has a higher precedence. If the record size that perl read is the expected record size, the LHS evaluates to one and the short circuit terminates.

      The better rule of thumb is to use or when you want everything else to happen first.

      If you know about problems in the perlfaq, however, you can send them to perlfaq-workers @ perl.org and we'll fix them up.

      --
      brian d foy <brian@stonehenge.com>
        In terms of your "rule of thumb," I like to say that || goes between expressions, and or goes between statements. It's kinda like how , goes between elements, but ; goes between statements. I'm not sure if my phrasing is any more clear to the uninitiated than talking in greek, though.

        --
        [ e d @ h a l l e y . c c ]

        Gah, you are right, and I should know better.
Re: "or die" versus "|| die"
by brian_d_foy (Abbot) on Jun 24, 2005 at 16:05 UTC

    The perlfaq is and has been maintained by several people, so you see a lot of different styles and conventions. Rather than enforce a particular style, I let the answers show that there is more than one way to do things, although I have also started noted the authors of each answer.

    The "best way" is up to you. The "or" version generally works out for people who don't like parentheses (since they don't use the parens' supreme precendence to define the order).

    --
    brian d foy <brian@stonehenge.com>
Re: "or die" versus "|| die"
by bart (Canon) on Jun 24, 2005 at 17:17 UTC
    || is very old, or is newer. The latter is preferred, the reason why you still see || so often is indeed because or is a more recent addition.

    And the difference is indeed just their precedence, or behaves more appropriately for this kind of functionality.

Re: "or die" versus "|| die"
by perlhaq (Scribe) on Jun 24, 2005 at 18:55 UTC
    Like others have said, you're better off sticking with "or" except for those few cases where the || is necessary for precedence reasons. Familiarize yourself with the operator precendence chart in the "perlop" manual page, print it out and tape it to your monitor if you have to in the beginning (eventually you'll know it instinctively).
    The few cases were I use || instead of "or" are constructions like these:
    my $var = $cgi->param('foo') || $default{'foo'}; # assign default value if none given
    my $var = $cgi->param('foo') || ''; # assign empty value if none given (to avoid warnings due to undef value)
    if ($verbose and $bar || $baz) { print "starting job $job_num\n" }
Re: "or die" versus "|| die"
by Anonymous Monk on Jun 25, 2005 at 01:34 UTC

      Indeed. I completely missed that.

      Thanks.

      Walking the road to enlightenment... I found a penguin and a camel on the way.....
      Fancy a yourname@perl.me.uk? Just ask!!!
Re: "or die" versus "|| die"
by davido (Archbishop) on Jun 25, 2005 at 04:43 UTC
Re: "or die" versus "|| die"
by aditya.singh (Acolyte) on Jun 27, 2005 at 09:20 UTC
    Both '||' and 'or' are similar. These operators allow you to perform one of the two operations, starting with the first operation on the left-hand side. If that evaluates to false, only then will right side of (||, or) will be evaluated.

    In this case, if your open() fails then the program will die.

    The difference comes when you use them in expressions. They have different precedence and '||' is evaluated before the 'or'. You can check perldoc perlop.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://469724]
Front-paged by Tanalis
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (10)
As of 2014-09-03 06:02 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite cookbook is:










    Results (35 votes), past polls