Re: trying to use IO::Handle



Richard Lee wrote:
why does below fail?

----- where it's failing -----
open my $source, "<", "/tmp/server.log"
or die "Could NOT open /var/log/server.log: $!";

$source is an opened filehandle.

my $file = new IO::Handle;

$file is an IO::Handle object but it is not related to any file.

while ($_ = $file->getline($source) ) {

You are trying to getline() from an object that is not associated with a file and $source is ignored because getline() does not take an argument and as the example from the documentation below shows you are not testing if the returned value is defined which may exit out of the loop before the end-of-file.


----------------------------

Uncaught exception from user code:
usage: $io->getline() at ./watch_int1_2.pl line 126
at /usr/lib/perl5/5.8.8/i386-linux-thread-multi/IO/Handle.pm line 411
IO::Handle::getline('IO::Handle=GLOB(0x9af8c5c)', 'GLOB(0x9b12380)') called at ./watch_int1_2.pl line 126
main::shove_it() called at ./watch_server.pl line 98


$io->getline
^^^^^^^^
Does not take an argument.


This works like <$io> described in "I/O Operators" in perlop
<http://search.cpan.org/perldoc?perlop#I/O_Operators> except that
it's more readable and can be safely called in a list context but
still returns just one line. If used as the conditional +within a
|while| or C-style |for| loop, however, you will need to +emulate
^^^^^

the functionality of <$io> with |defined($_ = $io->getline)|.
^^^^^^^^
defined() test required when used in while loop.


I was trying to speed up my program which has to go through huge server log (500Meg+) and when I was going over w/

while ($source) {

That won't work without the readline operator:

while ( <$source> ) {

Note that the built-in readline is short for:

while ( defined( $_ = <$source> ) ) {

Where the assignment to $_ and the defined test are applied by default.


}

I discovered(from Dprof) that it was using up too much CPU(it's on old system) and wanted to use a IO module to get down to lower level to gain some speed but I am not too familiar w/ using modules.. can someone help
on this?

IO::Handle is just an OO wrapper on top of Perl's built-in operators:

perldoc -m IO::Handle

[ SNIP ]

sub getline {
@_ == 1 or croak 'usage: $io->getline()';
my $this = shift;
return scalar <$this>;
}


So in the end you are just using Perl's <> readline operator but with the overhead of a method call.



John
--
Perl isn't a toolbox, but a small machine shop where you
can special-order certain sorts of tools at low cost and
in short order. -- Larry Wall
.