Given the pleasant spring weather as of late, I started thinking about golf. Then I came up with a few different ways to create and store each record. Some of mine are below. The problem is creating the mapping from the column name (from @fieldnames) to values (retrieved from split).#!/usr/bin/perl -w use strict; # first line has column headings my @fieldnames = split /,/, <>; # @entries = ( { Last => 'zacks', First => 'evan', ... }, ... ) my @entries; # create and store a record for each line of input while (<>) { my %h; @h{@fieldnames} = split /,/; push @entries, \%h; } foreach my $h (@entries) { foreach my $k (@fieldnames) { print "$k: $h->{$k}\n" } } __DATA__ sample input: Last,First,Address,Apt,City,St,Zip,Email,Notes zacks,evan,123 main,,ann arbor,mi,48104,evan@zacks.org,perlmonks++
Golf (or at least other solutions), anyone?# pretty much the same as above (weak, i know) while (<>) { my %h; push @entries, do { my %h; @h{@fieldnames} = split /,/; \%h }; } # different, but still using a temp var while (<>) { my @f = @fieldnames; push @entries, { map { shift @f => $_ } split /,/ }; } # hmm. gets rid of the temp var, but it's pretty ugly. while (<>) { push @entries, { map { push @fieldnames, shift @fieldnames; $fieldnames[-1] => $_ } split /,/ }; } # tye++ (see http://www.perlmonks.org/index.pl?node_id=44763) use mapcar; while (<>) { push @entries, { mapcar { @_ } \@fieldnames, [ split /,/ ] }; }
In reply to golfing hash slices by sacked
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |