Search code examples
perl

The correct way to read a data file into an array


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.


Solution

  • 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";
    }