The random error is, it's able to open the file (the die action never happens), but unable to read any data ($line is uninitialized)

Since your code isn't hitting the die() after the open() call, the program found the file and had permission to open it. Chances are good you just attempted to read an empty file.

As perlop will explain under the I/O Operators heading, the angled-bracket read returns undef in scalar context when you're at EOF (end-of-file.) If you care about this condition, you should test the definedness of $line before using it, and possibly report EOF as an error condition to the invoker of the script rather than try to use it.

I can reproduce the condition you're seeing by running the code shown at the bottom of this post (which I call y1.pl) with the following test. Note that I'm on a Unix-alike, so you may need to populate an empty file a different way as defined by your OS. Also note that I replace an undefined result with a notice that the line was in fact undefined, using the // operator. This should illustrate the problem I suspect you're having.

Test case:

cp /dev/null file.txt perl ./y1.pl echo "hello world" > file.txt perl ./y1.pl

y1.pl:

use strict; use warnings; my $file_src = 'file.txt'; open(my $fh, '<', $file_src) or die "open() failed: $!"; my $line = <$fh>; close($fh) or die "close() failed: $!"; printf( "Got a line: %s", $line // '<line-was-undef>' );

In reply to Re: Able to open file, unable to read by Apero
in thread Able to open file, unable to read by feiiiiiiiiiii

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.