4

How would I skip say line 9 while I'm parsing a text file?

Here's what I got

use strict; use warnings;
open(my $fh, '<', 'file.txt') or die $!;
my $skip = 1;
while (<$fh>){
    $_=~ s/\r//;
    chomp;
    next if ($skip eq 9)
    $skip++;
}

Not sure if this works but I'm sure there's a more eloquent of doing it.

ikegami
  • 367,544
  • 15
  • 269
  • 518
cooldood3490
  • 2,418
  • 7
  • 51
  • 66
  • 2
    I can only assume that `s/\r//` is there because you have [␍␊](http://stackoverflow.com/a/3098328/1337) terminated lines. If that is the case you should open your file with the [`:crlf`](http://perldoc.perl.org/functions/open.html) layer (`open( my $fh, '<:crlf', 'file.txt')` ) – Brad Gilbert Apr 13 '13 at 06:17

1 Answers1

13

You can use $.:

use strict; use warnings;
open(my $fh, '<', 'file.txt') or die $!;
while (<$fh>){
    next if $. == 9;
    $_=~ s/\r//;
    chomp;
    # process line
}

Can also use $fh->input_line_number()

Sinan Ünür
  • 116,958
  • 15
  • 196
  • 339
imran
  • 1,560
  • 10
  • 8
  • 2
    okay so `$.` is a special variable that stores the current input line number of the last filehandle that was read. I just read that that from this [SITE](http://www.kichwa.com/quik_ref/spec_variables.html). I didn't know that until today. Thanks – cooldood3490 Apr 03 '13 at 16:58
  • 4
    @cooldood3490 The correct place to check is the documentation installed along with your `perl`: `perldoc -v '$.'` Current version of the documentation is available on [perldoc.perl.org](http://perldoc.perl.org/perlvar.html#%24.) I would recommend staying away from web sites that spell the name of the language incorrectly. – Sinan Ünür Apr 03 '13 at 17:12
  • Instead of `$_=~ s/\r//;`, write `s/\r//`. Better yet, write `while (my $line = <$fh>) { $line =~ s/\s+\z//; }`. – Sinan Ünür Apr 03 '13 at 17:14
  • 3
    You don't even have to use [`$.`](http://perldoc.perl.org/perlvar.html#%24. "perldoc -v '$.'") directly, you can use [`..`](http://perldoc.perl.org/perlop.html#Range-Operators "perldoc perlop") in scalar context. `next if 9..9;` If you need to skip more lines: `next if 9..12;` – Brad Gilbert Apr 13 '13 at 06:08