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

RE: Parsing a file one line at a time

by autark (Friar)
on Jul 23, 2000 at 00:38 UTC ( #23923=note: print w/replies, xml ) Need Help??


in reply to Parsing a file one line at a time

Hi!

Actually you only need to do this:

open(FILE1, $ARGV[0]) || die "Error: $!\n"; @lines = <FILE1>;
This evaluated <FILE1> in list-context, and thus the whole file will be put in the @lines-array, one entry per line (or whatever you have assigned to $/)

So then, why didn't your code work as you expected ? Well - the line

@lines = $_;
assigns the variable $_ to the array @lines. You are declaring the contents of @lines each and every time through that loop. It's almost the same with variables:
$foo = $_;
this also redeclares the contents of $foo every time it is evaluated. With scalars we usually use the . (dot) operator or string concat. operator to avoid redeclaring its content:
$foo .= $_;
or:
$foo = $foo . $_;
So, with arrays we have something similar:
push @lines, $_;
That will add to @lines instead of redeclaring its contents.

Autark

Replies are listed 'Best First'.
RE: RE: Parsing a file one line at a time
by Anonymous Monk on Jul 23, 2000 at 21:08 UTC
    you (probably) might want to use some idomatic perl, its called 'slurp mode'. It means being able to take in (slurp) the whole file in one go, this is possible by temporarily 'undef'ining the File Seperator $\.
    open(FILE1, $ARGV[0]) || die "Error: $!\n"; { local $/; #value is restored at end this block undef $/; #'slurp mode' @lines = <FILE1>; #slurp all lines } #$/ is as back 'to normal', so nothing unexpected happens later
    local is 'sometimes' the 'right' way.
      Actually, "slurp" mode is used for reading the contents of a file into a scalar. You're using an array. If you assign a filehandle to an array, Perl just "understands" and reads the entire file into the array. This code works fine:
      open(FILE1, $ARGV[0]) || die "Error: $!\n"; @lines = <FILE1>;
      Cheers,
      Ovid

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://23923]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (4)
As of 2020-11-26 01:24 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?