Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

how can we read each line from a file onto an array?

by Anonymous Monk
on Apr 18, 2001 at 09:57 UTC ( #73439=perlquestion: print w/replies, xml ) Need Help??

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question: (files)

how can we read each line from a file onto an array?

Originally posted as a Categorized Question.

  • Comment on how can we read each line from a file onto an array?

Replies are listed 'Best First'.
Re: how can we read each line from a file onto an array?
by OeufMayo (Curate) on Apr 18, 2001 at 12:37 UTC
    my @lines = <FILE>;

    But beware, as the perlfaq 5 says:

    Whenever you see someone do this:

        @lines = <INPUT>;

    You should think long and hard about why you need everything loaded at once. It's just not a scalable solution. You might also find it more fun to use the the standard DB_File module's $DB_RECNO bindings, which allow you to tie an array to a file so that accessing an element the array actually accesses the corresponding line in the file.

Re: how can we read each line from a file onto an array?
by tye (Sage) on Apr 18, 2001 at 17:20 UTC
    my @lines= do { local(*ARGV); @ARGV="filename.txt"; <> }; is one way to avoid having to open the file explicitly, check for errors, and report them.
Re: how can we read each line from a file onto an array?
by davorg (Chancellor) on Apr 18, 2001 at 12:30 UTC
    open FILE, '/path/to/file' or die "Can't open file: $!\n"; my @array = <FILE>;

    All very simple :)

Re: how can we read each line from a file onto an array?
by abhishek_akj (Initiate) on Aug 26, 2009 at 10:19 UTC
    my @lines = <FILE>
    above loads the whole file at once in memory.

    Instead, you can do something like

    while(my $line=<FILE>){ do_something; }
    This code will still traverse the whole file, so wont be faster but it will load only one line at a time in the memory - helpful if you want to parse 4GB file and have only 2 GB RAM ;)
Re: how can we read each line from a file onto an array?
by Clachair (Acolyte) on Apr 24, 2001 at 13:45 UTC
    use IO::File; open ($fhi, $fi) || die "$!, Couldn't open file $fi"; @lines = $fhi->getlines; foreach $lines(@lines) { # Select only those lines with a HTML cell bg color spec; if ($lines =~ /^\s*<td bgcolor/) {push @List, $lines; } } closedir ($fhi, $fi);
    Clachair. Never lick a gift horse in the mouth.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (8)
As of 2021-04-21 10:34 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?