in reply to Efficiently compare sorted array vs another sorted array and pattern match
I made the script below (click "Read more...") a lot more formal than necessary to do what it does, just to make it clearer and easier to modify. Think of all the little functions as hooks you can modify to suit your needs.
There's one wrinkle that needs clarification, and it has to do with the issue of repeats. In the example you gave @array has no repeated elements, which seems reasonable, but I was not sure if it was fair to assume that the ordering of the lines in the file was "strict" (i.e. no two lines in the input file have the same entry in the final position), so the script below does not make this assumption. This is why the position in the array is advanced only if the word in the array is strictly less than the word coming from the file. If in fact it is possible to assume that the ordering of the lines in the file is strict, then you could make the code more symmetrical and also shave off a few nanoseconds from the running time by uncommenting the commented line; this will result in having both the position in the array and in the file advance whenever a match is found. I think it is better as it is, since it works equally well whether the input file is strictly ordered or not.
use warnings; use strict; my $word_a = next_from_array(); my $word_f = next_from_file(); while ( 1 ) { last unless defined $word_f and defined $word_a; if ( $word_f lt $word_a ) { $word_f = next_from_file(); } elsif ( $word_a lt $word_f ) { $word_a = next_from_array(); } else { process( current_line() ); # $word_a = next_from_array(); $word_f = next_from_file(); } } { INIT { reset_array(); } { my ( $i, @array ); sub reset_array { @array = qw( item1 item2 item4 item5 ); $i = 0; } sub next_from_array { return $i < @array ? $array[ $i++ ] : ( $i = 0, undef ); } } INIT { my $filename = shift || die "Usage: blah blah blah\n"; reset_file( $filename ); } { my ( $in, $line ); sub reset_file { my $filename = shift; use PerlIO::gzip; my $mode = '<:gzip'; open $in, $mode, $filename or die "can't read $filename: $!\n"; } sub next_from_file { local $_ = $line = <$in> and chomp; return defined $_ ? ( split /\t/ )[ -1 ] : ( reset_file(), undef ); } sub current_line { return $line; } } } sub process { local $| = 1; print shift; } __END__
HTH.% perl -le 'print join "\t", map 'item'.int(rand 500), 1..5 for 1..100 +0' \ | sort -k 5,5 | gzip > mongo.gz % perl 446183.pl mongo.gz item326 item362 item39 item84 item1 item378 item164 item305 item336 item1 item238 item431 item284 item452 item2 item115 item76 item230 item319 item4 item121 item479 item258 item301 item4 item3 item480 item187 item269 item4 item278 item327 item252 item459 item5
the lowliest monk
Update: Minor refactoring: tightened the scope of a few lexicals. Basic program structure remains unchanged.
|
|---|