Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

die on file open

by rgren925 (Initiate)
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
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 "...";

    means

    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 (Monsignor) 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?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (4)
As of 2014-07-26 18:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (178 votes), past polls