in reply to Best way to read line x from a file
my $line2 = (<FILE>)[9];
Your method evaluates <FILE> in list context, resulting in a file slurp. Then you index into only one line, and let the rest of the slurp fall into the bit-bucket.
I agree with Corion that Tie::File is a great solution.
But I couldn't leave well enough alone, and had to come up with yet another way to do it. This solution still reads through the file up until it gets to the desired line. There's no way around that unless your lines are fixed-length.:
my $linenum = 10; while ( my $line = <FILE>) { next unless $. == $linenum; # Process the one line here... last; # No need to continue. }
I hadn't seen anyone using $. yet. See perlvar.
Update:Added last; to the loop. Thanks for the reminder.
Dave
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: Best way to read line x from a file
by TomDLux (Vicar) on Mar 29, 2004 at 16:50 UTC |