Search code examples
perl

How do I populate an array with numbers found in lines of a file?


There are many solutions on here to similar scenarios as mine, but I can't adapt them to my specific needs.

I have a file where each line contains a name and a list of numbers. An example line:

Bradley Jones,65,69,71,72,75,71,65,74,69,71,72,75,71,65,65,69,71,72,75,71,65,74,69,71,72,75

How do I add each comma separated piece of data into elements of an array? The lines could just have a few numbers or have vastly more. I'd need to know that the first element contained a name and every following element would contain a number, however many were found.


Solution

  • How about something like

    open my $fh, '<', 'input.txt';
    
    while (<$fh>) {
        chomp;                   # removes the newline at end of the string
        my @array = split /,/;   # creates the array from the line
        my $name = shift @array; # removes the first element and puts it into $name
    
        # validate
        say 'Number in first column' if $name =~ /\d/;
        say 'Non-number in remaining columns' if grep { /\D/ } @array;
    
        # do something with @array
    }
    

    It turns each line into an array and then takes the first element out of the array and puts it into $name. Do something with @array before the next line is read. There's some very basic validation which really depends on your use case.