5

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;
1
  • I like twoHandsTwoCutsFunction function :) sub{map{s/^\s+//; s/\s+$//; $_}@_} Commented Aug 5, 2013 at 9:18

1 Answer 1

10

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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.