perlUser345 has asked for the wisdom of the Perl Monks concerning the following question:

I've been trying to do this for a week now, with no success. I have a csv file that has data in three columns and looks like this

NAME, IN, OUT
a, 10, 20
b, 10, 30
c, 50, 20
d, 20, 60

Then I take the IN and OUT numbers and do some processing on them which is not relevant. But at the end I output the IN and OUT in lists like this:
IN:
row1: 10, 50
row2: 20, 10

OUT:
row1: 20, 60
row2: 20, 30

This is all good so far, the problem is that I also want to give these IN and OUT lists by the name (for the values that correspond to more than one name, I just want to give them in the order they appear). In this case:
IN:
row1: a, c
row2: d, b

OUT:
row1: a, d
row2: c, b

Any help would be greatly appreciated.

Replies are listed 'Best First'.
Re: Linking data together
by GotToBTru (Prior) on Dec 03, 2015 at 20:02 UTC

    Store the value and it's associated line name together in the same variable as a hash.

    while(<DATA>) { ($name,@values) = split /,/; push @list, {name=>$name, value=>$_ } for @values }

    Perform your processing on $list[n]->{value}.

    Dum Spiro Spero
Re: Linking data together
by NetWallah (Canon) on Dec 04, 2015 at 01:41 UTC
    How about this:
    use strict; use warnings; chomp (my @keys = split /, /, <DATA>); # First row shift @keys; # Drop "NAME" my %h; for (<DATA>){ chomp ; my ($name,@items) = split /,\s*/ or next; $h{$name} = { map {$keys[$_] => $items[$_] =~/(\d+)/ } 0..$#keys } +; } printcol("IN",{row1=>["a","c"], row2=>["d","b"]}); printcol("OUT",{row1=>["a","c"], row2=>["d","b"]}); sub printcol{ my ($col, $r) = @_; print "$col:\n"; for (sort keys %$r){ print "$_ : ",join (", ", map{ $h{$_}{$col} } @{$r->{$_}}), "\n +"; } print "\n$col:\n"; for (sort keys %$r){ print "$_ : ",join (", ", @{$r->{$_}}), "\n"; } print "\n"; } __DATA__ NAME, IN, OUT a, 10, 20 b, 10, 30 c, 50, 20 d, 20, 60
    Output:
    IN: row1 : 10, 50 row2 : 20, 10 IN: row1 : a, c row2 : d, b OUT: row1 : 20, 20 row2 : 60, 30 OUT: row1 : a, c row2 : d, b

            Our business is run on trust. We trust you will pay in advance.