user2154731
user2154731

Reputation: 203

Perl push function gives index values instead of array elements

I am reading a text file named, mention-freq, which has data in the following format:

1

1

13

2

I want to read the lines and store the values in an array like this: @a=(1, 1, 13, 2). The Perl push function gives the index values/line numbers, i.e., 1,2,3,4, instead of my desired output. Could you please point out the error? Here is what I have done:

use strict;
use warnings;

open(FH, "<mention-freq") || die "$!";
my @a;
my $line;
while ($line = <FH>)
{
    $line =~ s/\n//;
    push @a, $line;
    print @a."\n";
}
close FH;

Upvotes: 5

Views: 655

Answers (1)

tchrist
tchrist

Reputation: 80384

The bug is that you are printing the concatenation of @a and a newline. When you concatenate, that forces scalar context. The scalar sense of an array is not its contents but rather its element count.

You just want

 print "@a\n";

instead.

Also, while it will not affect your code here, the normal way to remove the record terminator read in by the <> readline operator is using chomp:

chomp $line;

Upvotes: 10

Related Questions