Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris

die on file open

by rgren925 (Acolyte)
on Jan 11, 2011 at 19:55 UTC ( #881747=perlquestion: print w/ replies, xml ) Need Help??
rgren925 has asked for the wisdom of the Perl Monks concerning the following question:

Hi. I'm finding a peculiarity on file open (perl 5.8.3) that I can't find any explanation for in the doc. When I call open as a command: open $REQUESTFILE, '<', $aldbRequestFile || die "Unable to open ALdb Request file $aldbRequestFile: $!\n"; die never gets invoked when the file doesn't exist. Yet, when I call it as a function: open (my $REQUESTFILE, '<', $aldbRequestFile) || die "Unable to open ALdb Request file $aldbRequestFile: $!\n"; die works as expected. Can one of the perl gurus please explain this? Thanks, Rick Thanks very much ikegami and kennethk! Didn't even think of precedence

Comment on die on file open
Replies are listed 'Best First'.
Re: die on file open
by ikegami (Pope) on Jan 11, 2011 at 20:00 UTC

    You should be looking at operator precedence.

    open $fh, '<', $qfn || die "...";


    open($fh, '<', ($qfn || die("...")));

    You want

    open($fh, '<', $qfn) || die "..."; open($fh, '<', $qfn) or die "..."; open $fh, '<', $qfn or die "...";

    In general, one uses "or" when followed by die, return, next, last or similar, and one uses "||" the rest of the time.

Re: die on file open
by kennethk (Abbot) on Jan 11, 2011 at 20:02 UTC
    You are having an issue with Operator Precedence and Associativity. The two operators in question here are || (C style Logical Or) and , (Comma Operator). When you write

    open $REQUESTFILE, '<', $aldbRequestFile || die "Unable to open ALdb Request file $aldbRequestFile: $!\n";

    the || binds more tightly than the ,, so that means that the or is never evaluated so long as your file name is true. On the other hand, when you add parentheses, the or is tested against the return value of the open, and hence returns what you expect. Two possible solutions are to include the parentheses or use the lower precedence or (Logical or, Defined or, and Exclusive Or), which is more common in Perl:

    open $REQUESTFILE, '<', $aldbRequestFile or die "Unable to open ALdb Request file $aldbRequestFile: $!\n";

    As a side note, please wrap code in <code> tags - see Writeup Formatting Tips.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://881747]
Approved by kennethk
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (1)
As of 2015-10-10 18:22 GMT
Find Nodes?
    Voting Booth?

    Does Humor Belong in Programming?

    Results (257 votes), past polls