I suspect the redundancy and memory requirements in your one-liner is inefficient and
that a while loop would be not only more efficient but more
readable. Benchmark in progress ...
Update:After reviewing the original, its
not exactly the same, but I think still a fair enough
comparision :)
#!/usr/bin/perl -w
# About the fairest comparison I could think of at the moment
use strict;
use Benchmark;
my $file = "tst1.txt";
open(OUT, ">$file") or die "Can't open $file for output: $!";
for ("000000".."020000") {
print OUT "$_=abc|def|ghi|jkl\n";
print OUT "Ignore this line\n";
}
open(FH1, $file) or die "1 Can't open $file: $!";
open(FH2, $file) or die "2 Can't open $file: $!";
timethese(1, {
MAPIT=>\&map_it,
LOOPIT=>\&loop_it,
});
close FH1;
close FH2;
sub map_it {
my %author = map {/^\d{6}$/ ? $_ : [ split (/\|/, $_, 2 ]}
map { split( /=/, $_, 2 ) }
grep { /^\d{6}=[^|]+\|/ } <FH1>;
}
sub loop_it {
my %author;
while (<FH2>) {
next unless /^(\d{6})=(.+)\|/;
# Hmm, the above should really be:
# next unless /^(\d{6})=([^|].*)\|/;
# Whoops, forgot to limit the split to 2 elements here
# No big deal, results are still similar
$author{$1} = [ split(/\|/, $2) ];
}
}
# interesting different results
#Under activestate perl
Benchmark: timing 1 iterations of LOOPIT, MAPIT...
LOOPIT: 5 wallclock secs ( 4.62 usr + 0.00 sys = 4.62 CPU) @ 0
+.22/s (n=
)
(warning: too few iterations for a reliable count)
MAPIT: 28 wallclock secs (28.73 usr + 0.00 sys = 28.73 CPU) @ 0
+.03/s (n=
)
(warning: too few iterations for a reliable count)
#under Cygwin perl
$ ./tst
Benchmark: timing 1 iterations of LOOPIT, MAPIT...
LOOPIT: 4 wallclock secs ( 4.67 usr + 0.00 sys = 4.67 CPU) @ 0
+.21/s (n=
)
(warning: too few iterations for a reliable count)
MAPIT: 5 wallclock secs ( 5.22 usr + 0.00 sys = 5.22 CPU) @ 0
+.19/s (n=
)
(warning: too few iterations for a reliable count)
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.