... how to go to directly that line ...Inspired this seek-by-key approach:
You could create a simple index and then seek to the beginning of a line in order to re-read it. It might be suitable in a situation where you can keep the index in memory but not the whole file. But since the ratio of key-length to line-length is only approx. 1:5, (the smaller the ratio the better), there is probably no real gain for the given example data...
use strict; my %idx; # create index... while (<DATA>) { last if /# Prints/; # for this demo $idx{$1} = (tell(DATA) - length) if /^\s*(\S+)/; } # E.g., access each line in "natural" hash order (more/less random)... print "offset: <key> <line>\n"; foreach (keys %idx) { seek(DATA, $idx{$_}, 0); chomp (my $line = <DATA>); printf("%6d: %-7s <%s>\n", $idx{$_}, "<$_>", $line); } __DATA__ data1 122 1223 12223 12223 data2 12122 12223 122223 122223 data3 13422 134223 4512223 982223 data4 23432 3432 234234 789879 data5 5635 9786 23423 2323423 # Prints offset: <key> <line> 486: <data4> < data4 23432 3432 234234 789879> 418: <data2> < data2 12122 12223 122223 122223> 451: <data3> < data3 13422 134223 4512223 982223> 518: <data5> < data5 5635 9786 23423 2323423> 390: <data1> < data1 122 1223 12223 12223>
In reply to Re: random search in file
by Perlbotics
in thread random search in file
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |