The main advantage of using the object-oriented IO::File interface is the ability to create new anonymous filehandles without worrying about namespace collision. Also you get a scalar that you can pass around to other subroutines without special treatment**. Furthermore, you don't have to close the filehandle explicitly before exiting the subroutine that uses it; this is done automatically when the filehandle object goes out of scope.
{
use IO::File;
my $f = IO::File->new($file);
# no need to close
}
This method is not as fast as the built-in open/close function, but it is more flexible to use, and makes the code structually cleaner and easier to work with.
** From Perl 5.6 onwards, you can do open $filehandle, .... But that is not as portable as IO::File, because the IO::File module also works on older version of Perl.
Update: I googled around and found some interesting articles in support of using IO::File -
GC vs. reference counting
Perl has a form of garbage collection, but it uses a simple scheme called reference counting. Simply put, each Perl object keeps a count of the number of other objects pointing (referencing) itself. When the count falls to zero, nothing is pointing at this object, and so the object can be freed.
Reference counting is not considered as serious garbage collection by computer scientists, yet it has one big practical advantage over full garbage collectors. With reference counting, you can avoid many explicit calls to close/closedir in code. For example:
foreach (@files)
{
my $io = new IO::File "< $_" or die;
# read from $io
}
This Perl code iterates over a list of @files, opening and reading each one. There is no need to close the $io file handle at the end of the loop. Because Perl uses reference counting, as soon as we reach the end of the loop, the $io variable goes out of scope, so the reference count on the file object goes to zero, and it is immediately freed (ie. closed).
As always with Perl, there's more than one way to do it. Some people like apples but others like oranges. :-)
| [reply] [d/l] [select] |
Ok, cool. Thanks for pointing these pros to using IO::File; you gave me a new module to think about using, as well as provided the reasoning behind using it so other monks can make a more informed choice.
Also you get a scalar that you can pass around to other subroutines without special treatment.
open $fh, '<', $_ or die; ... or am I missing something?
| [reply] [d/l] |
Open with a scalar reference is a relatively new thing introduced to Perl (since 5.6), and earlier versions of Perl would break. IO::File is more portable and should work on older versions of Perl still out there.
| [reply] |