in reply to indefinite number of columns
If you have a header line in your data, you might want to consider to use a hash of arrays. Each array would contain one of your columns and could be adressed by the name given in the header.
use strict; use warnings; use Data::Dumper; my $n = 4; # number of columns, given as user input my %hcolumns; # this is the hash of the columns you are looking for my @header = split /,/,<DATA>; # pls use Text::CSV for any real work chomp @header; while(<DATA>){ chomp; my @record = split /,/; # pls use Text::CSV for any real wo +rk for (0..$n-1) { push @{ $hcolumns{$header[$_]} }, $record[$_]; + } } print Dumper \%hcolumns; # hash of columns __DATA__ Name,FirstName,Instrument Mangelsdorff,Albert,Trombone Parker,Charlie,Trumpet Coltrane,John,Tenor Evans,Bill,Piano
The number of columns can still be provided by the user. In this example here, I have chosen a number larger that the available columns resulting in an empty column (and some warnings when running the script).
|
|---|