Todd Wade <[EMAIL PROTECTED]> wrote:

> "Gary Stainburn" <[EMAIL PROTECTED]> wrote in message
> news:[EMAIL PROTECTED]
[...]
> > One thing you forgot was to close the file.  Also, don't 
> > forget that you can do it with less typing:

Closing files is optional in Perl ;-) Filehandles
will either be closed when the program terminates
when the filehandle is opened the next time.

> > $file = "/location/of/header.incl";
> > open (FH, "$file") or die "Cannot open file $file $!";

If you wanted to pipe other stuff than just plain
text, then 

    binmode(FH);

would be a good idea for portability.

> > print while(<FH>);

This is bad because it first pulls in the file to
build the list.

> > close(FH);

> print <FH>;
> 
> print takes a list of arguments:

Just to be nit-picking (and to repeat what I learned
from a M.J. Dominus talk at YAPC::EU this year ;-))

"print'ing a list is slower than printing a single
(large) scalar."

In this particular case it might be worthwhile to
use "slurping": We create a scope in which the input
record separator $/ is temporarily set to undef.
Reading from <IN> then returns just a single record.

The payoff - printing is nearly twice as fast.

#!/usr/bin/perl -w

use strict;
use Benchmark;

my $file = "out.txt";
my $count = 20000;

open( OUT, ">$file") or die "Can't open '$file':$!";

print "print using a scalar:\n";
timethis( $count, 'open(IN, "$0"); { local $/; undef $/; print OUT <IN>; };
close( IN)' );

close( OUT );
unlink $file;

open( OUT, ">$file") or die "Can't open '$file':$!";

print "print using a list:\n";
timethis( $count, 'open(IN, "$0"); print OUT <IN>; close( IN)' );

close( OUT );
unlink $file;
__END__
print using a scalar:
timethis 20000:  6 wallclock secs ( 2.85 usr +  2.44 sys =  5.30 CPU) @
3775.72/s (n=20000)
print using a list:
timethis 20000: 11 wallclock secs ( 7.88 usr +  2.67 sys = 10.56 CPU) @
1894.84/s (n=20000)

Cheers,
Thomas

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to