sacked has asked for the wisdom of the Perl Monks concerning the following question:
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 /,/ ] }; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: golfing hash slices (Russ = 57)
by Russ (Deacon) on Apr 13, 2001 at 08:55 UTC | |
by dkubb (Deacon) on Apr 13, 2001 at 10:21 UTC | |
by sacked (Hermit) on Apr 13, 2001 at 12:06 UTC | |
|
Re: golfing hash slices
by riffraff (Pilgrim) on Apr 13, 2001 at 00:27 UTC | |
|
Re: golfing hash slices
by petral (Curate) on Apr 13, 2001 at 08:57 UTC | |
|
Re: golfing hash slices
by premchai21 (Curate) on Apr 13, 2001 at 02:17 UTC |