Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses

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 the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (6)
As of 2016-06-26 20:04 GMT
Find Nodes?
    Voting Booth?
    My preferred method of making French fries (chips) is in a ...

    Results (331 votes). Check out past polls.