http://qs321.pair.com?node_id=407197


in reply to Making an array out of each line in a file

open FILE, '<', $filename or die "Can't open $filename: $!\n"; my @lines = <FILE>; close FILE or die "Can't close $filename: $!\n";

will fill @lines. See also the $/ variable.

--
Yours in pedantry,
F o x t r o t U n i f o r m

"Anything you put in comments is not tested and easily goes out of date." -- tye

Replies are listed 'Best First'.
close or die
by PerlingTheUK (Hermit) on Nov 11, 2004 at 22:34 UTC
    This caught my eye.

    Sorry for being pedant but we are opening files here, so - unless you mistype your file handle, - you can always close a filehandle. Or am I wrong?
    So there is no benefit of dieing on close. If we do not need to reset $., we need not even close it.

    Cheers,
    PerlingTheUK
      Sorry for being pedant but we are opening files here, so - unless you mistype your file handle, - you can always close a filehandle. Or am I wrong?

      No need to apologize for being pedantic :-). I can't think of a situation where close would fail on a plain old file on a local filesystem; for that, it's just habit. But networked filesystems, sockets, pipes, and so on can mess up close; besides, Always Check System Call Return Values is a good habit to get into.

      --
      Yours in pedantry,
      F o x t r o t U n i f o r m

      "Anything you put in comments is not tested and easily goes out of date." -- tye

        According to man 2 close (FreeBSD, OpenBSD and OS X) the two cases are:

        ERRORS Close() will fail if: [EBADF] D is not an active descriptor. [EINTR] An interrupt was received.

        </unecessarily complete information>

        But agreed, always checking the return value from system calls is good practice (just like you should always check your optics before testing your high powered laser when that jerk Kent's around . . . </Real Genius>).

        Update: Ooop, tilly is correct below. Perl's close is more akin to fclose(3) than close(2) and can return with errno of any of the errors from close(2) or fflush(3) (and fflush(3) in turn may set errno if an underlying write(2) failed).

        Thanks,
        I sometimes need some help with my English. Besides I think the original request was rather lacking to understand that
        my ( $a, $b, ... $z )
        is acutally an array. So it was my intention - and even though it was counter productive in the end - to avoid confucion of what is actually going on between open and close.
        BTW, my choice for reading a file into an array still is File::Slurp which was discussed quite exhaustively recently in a thread i just cannot find right now.

        Cheers,
        PerlingTheUK