Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

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

by Anonymous Monk
on Apr 18, 2001 at 09:57 UTC ( [id://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 my $fhi, '<', $fi or die "$!, Couldn't open file $fi"; my @lines = $fhi->getlines; for my $line ( @lines ) { # Select only those lines with a HTML cell bg color spec; if ( $line =~ /^\s*<td bgcolor/) { push @List, $line; } } close $fhi;

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (5)
As of 2024-04-18 14:43 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found