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

Re: from txt file to array

by thanos1983 (Parson)
on Jun 22, 2017 at 09:13 UTC ( [id://1193264]=note: print w/replies, xml ) Need Help??


in reply to from txt file to array

Hello WisDomSeeKer34,

Although the fellow Monks have replied to your question, I would like to add something extra.

On your question you are asking on how to process one file, and the monks have provided you the answer. I would like to add here that while loop is faster than straight opening a file in an array but also to add using a hash to keep track of the content of multiple files.

Sample of benchmark script and hash solution commented:

#!usr/bin/perl use strict; use warnings; use Data::Dumper; # use Benchmark qw(:all) ; # WindowsOS use Benchmark::Forking qw( timethese cmpthese ); # LinuxOS my @preserved = @ARGV; =Hash Of Arrays my %HoA; while (<>) { chomp; push @{ $HoA{$ARGV} }, $_; } continue { close ARGV if eof; } print Dumper \%HoA; __END__ $ perl test.pl in.txt out.txt $VAR1 = { 'in.txt' => [ 'Sample of text line 1', '', 'Sample of text line 2' ], 'out.txt' => [ 'Sample of text line 1 second file', '', 'Sample of text line 2 second file' ] }; =cut sub while_loop { my @output; @ARGV = @preserved; # restore original @ARGV while (<>) { chomp; push @output, $_; } continue { close ARGV if eof; } return; } sub file_to_array { @ARGV = @preserved; # restore original @ARGV chomp (my @data = <>); close ARGV if eof; return; } my $results = timethese(10000000, { Array => \&file_to_array, While => \&while_loop }, 'none'); cmpthese( $results ); __END__ $ perl test.pl in.txt in2.txt Rate Array While Array 115513/s -- -4% While 120846/s 5% --

Maybe you are not interested in opening multiple files (today) but what about (tomorrow)?

Update: One minor thing also to add here. Always always remember to close your file handles. Why? read this: Why do we need to close filehandles?.

Update2: Minor thing updating @ARGV to $ARGV in Hash Of Arrays (HoA) solution.

Hope this helps, BR.

Seeking for Perl wisdom...on the process of learning...not there...yet!

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (3)
As of 2024-04-25 12:49 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found