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;
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With