Anonymous Monk,
Given that I have no idea how large your files are, reading everything into memory might not be feasible. OTOH, looping through file2 as many times as there are entries in file1 may also be too time consuming. I have comprimised by caching the offset in file2.
#!/usr/bin/perl
use strict;
use warnings;
my $file_1 = $ARGV[0] || 'file1.txt';
my $file_2 = $ARGV[1] || 'file2.txt';
open (FILE1, '<', $file_1) or die "Unable to open $file_1 for reading
+: $!";
open (FILE2, '<', $file_2) or die "Unable to open $file_2 for reading
+: $!";
my %offset = ( _pos => 0 );
while ( <FILE1> ) {
chomp;
if ( defined $offset{ $_ } ) {
seek FILE2, $offset{ $_ }, 0;
print scalar <FILE2>;
next;
}
else {
seek FILE2, $offset{_pos}, 0;
my $pos = tell FILE2;
while ( my $line = <FILE2> ) {
my ($col1) = $line =~ /^(\d+)/;
$offset{ $col1 } = $pos;
$pos = tell FILE2;
if ( $col1 eq $_ ) {
print $line;
$offset{_pos} = $pos;
last;
}
}
}
}
This is fully functional and should be a comprimise between speed and memory.
Update: Added optimization so that each line from file 2 is read a maximum of 2 times
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.