So I'm pretty new to Perl, only been learning it for 1 week. I'm trying to read only a specific range of lines into an array. If I print $_ inside the if statement, it list exactly what i want stored into my array. But storing $_ into my array and then print @array outside the while shows nothing. I'm not sure what I should do. Reason why I'm trying to store it into an array is too get certain information from the columns, therefore needing an array to do so. Thanks for your help. Its probably really simple for you guys
use strict;
use warnings;
my $filename = 'info.text';
open my $info, $filename or die "Could not open $filename: $!";
my $first_line = 2;
my $last_line = 15;
open(FILE, $filename) or die "Could not read from $filename, program halting.";
my $count = 1;
my @lines;
while(<FILE>){
if($count > $last_line){
close FILE;
exit;
}
if($count >= $first_line){
#print $_;
push @lines, $_;
}
$count++;
}
print @lines;
Perl actually has a variable, $.
, that represents the current line from the most recently used File handle:
From perldoc -v $.
:
HANDLE->input_line_number( EXPR )
$INPUT_LINE_NUMBER
$NR
$.
Current line number for the last filehandle accessed.
Each filehandle in Perl counts the number of lines that have been read from it. (Depending on the value of $/ , Perl's idea of what constitutes a line may not match yours.) When a line is read from a filehandle (via readline() or <> ), or when tell() or seek() is called on it, $. becomes an alias to the line counter for that filehandle.
You can use this variable to drastically simplify your code:
use strict;
use warnings;
my $filename = 'info.text';
open(FILE, $filename)
or die "Could not read from $filename, program halting.";
my @lines;
while(<FILE>){
next unless $. >= 2 && $. <= 15;
push @lines, $_;
}
close FILE;
print @lines;
You can wrap this code, or a modified version in a subroutine that accepts a filehandle, starting line, and ending line to make it more flexible.
Another note that is unrelated to your problem at hand, it is recommended that you always use three argument open.