Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options

"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?


Walking the road to enlightenment... I found a penguin and a camel on the way.....
Fancy a Just ask!!!

Replies are listed 'Best First'.
Re: "or die" versus "|| die"
by jeffa (Bishop) 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';


    (the triplet paradiddle with high-hat)
Re: "or die" versus "|| die"
by trammell (Priest) on Jun 24, 2005 at 15:17 UTC
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 <>
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.


        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 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 davido (Archbishop) on Jun 25, 2005 at 04:43 UTC
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 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 @ and we'll fix them up.

      brian d foy <>
        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 Anonymous Monk on Jun 25, 2005 at 01:34 UTC

      Indeed. I completely missed that.


      Walking the road to enlightenment... I found a penguin and a camel on the way.....
      Fancy a Just ask!!!
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.

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';


      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!


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


      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

      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.

      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!

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

      Don't fool yourself.

        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

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://469724]
Front-paged by Tanalis
Eily thinks vrk is a cookie monster
talexb thinks the term 'cookie monster' is unnecessarily drogatory ;) and takes a cookie as well. Mmmm. Delicious cookies.
[davido]: A tool as pretentious as Test::Perl::Critic ought not fail to install because one of its dependencies failed to pull in List::MoreUtils.
[davido]: ...and

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (11)
As of 2017-04-25 16:00 GMT
Find Nodes?
    Voting Booth?
    I'm a fool:

    Results (458 votes). Check out past polls.