0
votes

I am trying to open a file and pass it to a function and read in 100 line chunks. To do this I did:

open my $fh, '<', $file or die "Unable to open the file: $!";
#get the header out
my $header = <$fh>;
my @columns =  get_column_headers($header);
getData($fh, 100);

...

sub getData {
  my $fh = shift;
  my $maxLines = shift;
  my $count = 0;
  while (my $line = <$fh> && $count < $maxLines) {
        print "line is : $line \n"; 
  }
}

This prints line is : 1
If I do a print ref on $fh after open and when I pass it to getData it prints out GLOB. How do I actually retrieve the remaining lines instead of "1" which I assume is the number of lines it read? What am I doing wrong?

2

2 Answers

5
votes

Just a precedence issue.

my $line = <$fh> && $count < $maxLines

means

my $line = ( <$fh> && $count < $maxLines )

so add parens

( my $line = <$fh> ) && $count < $maxLines

Oh, and you forgot to increment $count.

( my $line = <$fh> ) && ++$count <= $maxLines
2
votes

Have a read of http://perldoc.perl.org/perlop.html#Operator-Precedence-and-Associativity

(my $line = <$fh> && $count < $maxLines) is being interpretted as (my $line = (<$fh> && $count < $maxLines)), returning a true value (1) to $line.

it is better written as (my $line = <$fh> and $count < $maxLines) or ((my $line = <$fh>) && ($count < $maxLines)).