in reply to How do I read the contents of a file?

Seeing that no one is using IO::File to open files, I will state the alternative (preferred) method of file handling. I know this is an old question, I am just stating the obvious here, but this post is to offer guidance to the beginner, isn't it?

To open a file with IO::File,
use IO::File; $f = new IO::File "filename.txt", "r";
To read data from the file, just use the <> operator:
while (<$f>) { ... do something here... }
To close the file afterwards, simply undefine $f:
undef $f;

Replies are listed 'Best First'.
Re: Answer: How do I read the contents of a file?
by davido (Cardinal) on Sep 12, 2003 at 08:56 UTC
    If you're a fan of lexical scoping, it could be used to improve the previous example by removing the need to undef $f in order to close the handle. With lexical scoping, when $f falls out of scope, the file is closed implicitly. See the following example:

    use strict; use warnings; use IO::File; { my $f = new IO::File "filename.txt", "r"; while (<$f>) { # do your stuff } }

    As the outter pair of curly brackets closes, so does the block in which $f was defined, and thus $f falls from scope, and thus is undefined, and thus the file to which it refers is implicitly closed.

    Dave

    "If I had my life to do over again, I'd be a plumber." -- Albert Einstein

Re: Answer: How do I read the contents of a file?
by NetWallah (Canon) on Sep 12, 2003 at 21:03 UTC
    Since this is a newbie tutorial, it may be worth explaining that the contents of the record read are available in the $_ variable, in the block "... do something here...".

    For example, if you wanted to PRINT the file, you would say:

    while (<$f>) { print $_; # $_ contains the record most recently read # The "$_" is implied if omitted, so you could simply # say: print; # # If you need to append a newline after each record, # use : print "$_\n"; }
Re: Answer: How do I read the contents of a file?
by ysth (Canon) on Nov 20, 2003 at 08:34 UTC
    Seeing that no one is using IO::File to open files, I will state the alternative (preferred) method of file handling.
    I've seen this designation "preferred" several times now. This isn't an attack, but a genuine question. What is the source for this? I see in perl5004delta that the IO:: family is preferred over the older FileHandle module, but nowhere do I see any reference to open() being no longer the preferred way to open files.