Perl read line by line
Solution 1:
If you had use strict
turned on, you would have found out that $++foo
doesn't make any sense.
Here's how to do it:
use strict;
use warnings;
my $file = 'SnPmaster.txt';
open my $info, $file or die "Could not open $file: $!";
while( my $line = <$info>) {
print $line;
last if $. == 2;
}
close $info;
This takes advantage of the special variable $.
which keeps track of the line number in the current file. (See perlvar)
If you want to use a counter instead, use
my $count = 0;
while( my $line = <$info>) {
print $line;
last if ++$count == 2;
}
Solution 2:
With these types of complex programs, it's better to let Perl generate the Perl code for you:
$ perl -MO=Deparse -pe'exit if $.>2'
Which will gladly tell you the answer,
LINE: while (defined($_ = <ARGV>)) {
exit if $. > 2;
}
continue {
die "-p destination: $!\n" unless print $_;
}
Alternatively, you can simply run it as such from the command line,
$ perl -pe'exit if$.>2' file.txt
Solution 3:
you need to use ++$counter
, not $++counter
, hence the reason it isn't working..