Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl read line by line

Tags:

perl

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); 
like image 530
user534009 Avatar asked Dec 22 '10 01:12

user534009


People also ask

How do I read the contents of a file in Perl?

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);

How do I read the first line of a file in Perl?

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.


2 Answers

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; } 
like image 157
friedo Avatar answered Sep 20 '22 17:09

friedo


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 
like image 42
NO WAR WITH RUSSIA Avatar answered Sep 23 '22 17:09

NO WAR WITH RUSSIA