Is there no way in perl to start reading a file from a specific line number. Whenever we read a file in perl we do while(<$fileHandler>)
which makes the perl interpreter to read the file from beginning. What to do if I don't want to read these lines?
2 Answers
You can skip lines from the beginning, and start processing with $start_line
,
my $start_line = 10;
while(<$fileHandler>) {
next unless $. == $start_line .. undef;
# ..
}
The range operator ..
also provides the following shorthand:
If either operand of scalar ".." is a constant expression, that operand is considered true if it is equal (
==
) to the current input line number (the$.
variable).
Therefore the above can be reduced to:
while(<$fileHandler>) {
next unless 10 .. undef;
# ..
}
-
@JohnC yes; it only shows how to effectively skip the lines. – mpapec Jun 08 '14 at 12:42
-
OMG! This may be one of the few times I'm actually cool with the use of [`unless`](http://perldoc.perl.org/functions/unless.html). It's so rare that I forget examples. Thanks for sharing ;) – Miller Jun 08 '14 at 22:38
-
@Miller I didn't believe myself what did I just wrote. ;) btw, `if not` still does the job. – mpapec Jun 09 '14 at 06:41
Because you can't know how long a line will be you must read from the beginning of the file.
If you know how wide your line will be because you have a fixed line width, or some other scheme then you can seek to that position in your file. Otherwise you have to read every character and search for the 'special' new line characters.
A text file is just a long list of characters. There is nothing special about lines.

- 4,276
- 2
- 17
- 28
-
3This is not a problem specific to Perl as the OP's question implies. – user3183018 Jun 08 '14 at 12:54
-
Yes it's not specific to perl but it's a good explanation of the problem :) – mamod Jun 08 '14 at 15:39