open my $FH, "/tmp/test.txt" || die "Failed to open /tmp/test.txt: $!\ +n";

BTW: This statement from the OP has a bug. The relatively high precedence of the  || logical-or operator means that the truth value of the file name is logical-ored with the value returned by the die built-in (which, of course, never returns). Because a file name will almost always be true ('0' is the only one I can think of that would be false), the short-circuiting of the  || operator means that  die will almost never be evaluated and the statement will seem to 'work'. The  or logical operator has a sufficiently low precedence to make this really work. (See perlop.)

So the correct version of this idiom is something like
    open my $FH, "/tmp/test.txt" or die "Failed to open /tmp/test.txt: $!\n";
or (less elegantly IMHO)
    open(my $FH, "/tmp/test.txt") || die "Failed to open /tmp/test.txt: $!\n";

Update: This bug is hinted at by the fact that in the deparse of toolic's reply, the  die sub-expression has vanished! This is because the literal file name  "/tmp/test.txt" is always true, so the compiler softly and silently optimizes the  die away.


In reply to Re: $_[0] fails for file handle? by AnomalousMonk
in thread $_[0] fails for file handle? by sophate

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.