I have a simple Perl script to read a file line by line. Code is below. I want to display two lines and break the loop. But it doesn't work. Where is the bug?
$file='SnPmaster.txt'; open(INFO, $file) or die("Could not open file."); $count = 0; foreach $line (<INFO>) { print $line; if ($++counter == 2){ last; } } close(INFO);
The main method of reading the information from an open filehandle is using the operator < >. When < > operator is used in a list context, it returns a list of lines from the specified filehandle. The example below reads one line from the file and stores it in the scalar. $firstchar = getc (fh);
Note: since ->lines is returning a list, calling it without the brackets around $firstline it will be assigned the number of lines which have been read from filename. txt : 1 (or 0 if it's empty). You might want to chomp $firstline; or the value could have a newline at the end and that might not be something you want.
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; }
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With