use IO::File;
my $fh = IO::File->open("/etc/passwd")
or die "constructor failed: $!";
while (<$fh>) { # $fh acts like any filehandle
print "a password line is $_";
}
close $fh; # nearly all built-ins can use IO::File
Here, $fh is constructed using the
open class method of IO::File,
and then used in places where ordinarily you'd use a
traditional (bareword) filehandle. Furthermore, you also get some
additional methods:
if ($fh->opened) { ... } # file is open
$fh->blocking(0); # make I/O be "non-blocking" if supported
Note that you can't use the more traditional
filehandle read or filehandle print operations because the reading
and writing filehandles weren't in a simple scalar
variable. Rewrite that loop to see if copying the handles is easier:
while (@handlepairs) {
@handlepairs = grep {
my ($IN, $OUT) = @$_;
if (defined(my $line = <$IN>)) {
print $OUT $line;
} else {
0;
}
} @handlepairs;
}
This scenario is arguably better. Most of the time, simply copying
the complexly referenced value into a simple scalar is easier on the
eyes. In fact, another way to write that loop is to get rid of the
ugly if structure:
while (@handlepairs) {
@handlepairs = grep {
my ($IN, $OUT) = @$_;
my $line;
defined($line = <IN>) and print $OUT $line;
} @handlepairs;
}