Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight

Re: indefinite number of columns

by hdb (Prior)
on Jul 15, 2013 at 14:21 UTC ( #1044388=note: print w/replies, xml ) Need Help??

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).

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1044388]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (7)
As of 2017-01-16 17:22 GMT
Find Nodes?
    Voting Booth?
    Do you watch meteor showers?

    Results (151 votes). Check out past polls.