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.
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.
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.
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"; }
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With