Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl push function gives index values instead of array elements

Tags:

arrays

perl

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;
like image 860
user2154731 Avatar asked Aug 05 '13 00:08

user2154731


1 Answers

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;
like image 70
tchrist Avatar answered Oct 30 '22 15:10

tchrist