Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The correct way to read a data file into an array

Tags:

perl

I have a data file, with each line having one number, like

10 20 30 40 

How do I read this file and store the data into an array?

So that I can conduct some operations on this array.

like image 650
user297850 Avatar asked Jan 22 '12 18:01

user297850


People also ask

How do you read data into an array?

In Java, we can store the content of the file into an array either by reading the file using a scanner or bufferedReader or FileReader or by using readAllLines method.

How do I read an array from a file in Perl?

Just reading the file into an array, one line per element, is trivial: open my $handle, '<', $path_to_file; chomp(my @lines = <$handle>); close $handle; Now the lines of the file are in the array @lines . You should really handle the case for the 'open' failing, either by checking the return value or using autodie.


2 Answers

Just reading the file into an array, one line per element, is trivial:

open my $handle, '<', $path_to_file; chomp(my @lines = <$handle>); close $handle; 

Now the lines of the file are in the array @lines.

If you want to make sure there is error handling for open and close, do something like this (in the snipped below, we open the file in UTF-8 mode, too):

my $handle; unless (open $handle, "<:encoding(utf8)", $path_to_file) {    print STDERR "Could not open file '$path_to_file': $!\n";    # we return 'undefined', we could also 'die' or 'croak'    return undef } chomp(my @lines = <$handle>); unless (close $handle) {    # what does it mean if close yields an error and you are just reading?    print STDERR "Don't care error while closing '$path_to_file': $!\n"; }  
like image 131
Sean Avatar answered Oct 21 '22 14:10

Sean


There is the easiest method, using File::Slurp module:

use File::Slurp; my @lines = read_file("filename", chomp => 1); # will chomp() each line 

If you need some validation for each line you can use grep in front of read_file.

For example, filter lines which contain only integers:

my @lines = grep { /^\d+$/ } read_file("filename", chomp => 1); 
like image 33
Taras Avatar answered Oct 21 '22 15:10

Taras