Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"

reading a file, put into array. Missing first line

by kaka_2 (Sexton)
on Oct 11, 2013 at 16:51 UTC ( #1057923=perlquestion: print w/replies, xml ) Need Help??
kaka_2 has asked for the wisdom of the Perl Monks concerning the following question:

Hello Monks,

I am reading a file and then putting it into an array but resulted array has always 1st line of file missing.

Here is my code

my $file = 'filename.txt'; my @2comp; open (my $fh, '<', $file) or die "cant open : $!"; while(<$fh>) { @2comp = <$fh>; } close $fh; @2comp = sort(@2comp); print "@2comp";

file "filename.txt" has 2 lines but array will show only second. i put more lines in file and i see that always first line of file is missing

What wrong i am doing? -KAKA-

Replies are listed 'Best First'.
Re: reading a file, put into array. Missing first line
by hdb (Monsignor) on Oct 11, 2013 at 16:59 UTC

    In the while statement you read the first line and in the next line you assign the rest of the file to the array. That way you lose the first line. Just remove the while loop alltogether and it should work.

Re: reading a file, put into array. Missing first line
by toolic (Bishop) on Oct 11, 2013 at 17:12 UTC
    You should always post the code you are running. What you posted doesn't compile.

    With the previous suggestion, here is a simplified version of your code:

    use warnings; use strict; my $file = 'filename.txt'; open my $fh, '<', $file or die "cant open : $!"; my @comp = sort <$fh>; close $fh; print "@comp";

      Thank you correcting me. and sorry about not able to post the actual code. copy paste is not allowed from citrix terminal and in that case i have to type it here manually. is there a option of attaching image ?

Re: reading a file, put into array. Missing first line
by exilepanda (Pilgrim) on Oct 12, 2013 at 15:48 UTC
    First, @2comp is not a valid variable name.

    To you question. The first line was missed because you already read it at your  while(<$fh>), which you didn't take care of it in the rest of your code.

    Besides, since you read your handle like this : @2comp =<$fh> ( again, @2comp is invalid var name ), this will be considered as a wantarray mode, so the rest of lines in the handle will be read and put into your array, which make your while loop meaningless.

    To correct this, you may either:

    @data = <$fh>; ( without the while loop ) or push @data, $_ while (<$fh>);

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1057923]
Approved by toolic
Front-paged by toolic
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (10)
As of 2018-05-25 17:49 GMT
Find Nodes?
    Voting Booth?