In the spirit of TWTOWTDOI, a variant of
fmerges's solution to use hash slices:
my %g = ();
my @innerKeys = qw/ specie gener age haircolor /;
while(<INFO>) {
my @vals = split /,/, $_;
my $name = shift @vals;
@{$g{$name}}{ @innerKeys } = @vals;
}
On a related note, I happened to just now be working with similar code that additionally leverages
Text::CSV so that you could have a line like
"Mr. Jones, Jr.",human,male,47,gray
my $csv = Text::CSV->new();
open FILE, $filename or die "couldn't open file '$filename': $!";
# if the file has colnames in the first row, do this:
$_ = <FILE>;
$csv->parse($_);
my @cols = $csv->fields();
# otherwise, manually define them:
my @cols = qw/ name specie gener age haircolor /;
while(<FILE>){
# let Text::CSV do the hard work.
$csv->parse($_);
# this turns blanks into undef's -- remove the "map {}" part if bl
+anks are ok.
my @vals = map { !defined($_) || $_ eq '' ? undef : $_ } $csv->fie
+lds();
# This hashes the whole row
my $row = { map { $cols[$_] => $vals[$_] } 0 .. $#cols };
# Now do whatever you need with it.
$g{ $row->{name} } = $row;
# Or a common/generic usage might be:
push @rows, $row;
}
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
|
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.