in reply to Stuck while learning about the hash
Hrmm... I might be really off here but wouldn't this construct be simpler? (pretty new to perl as well and not fully conversant with the intricacies of hashes)
#!/usr/bin/perl -w use strict; my %data; open DB, "db.txt"; while (<DB>) { @_ = split/[\t,|\n]/; $data{ $_[0] } = { @_[1..$#_] }; } close DB;
I tried shift @_ then just @_ in the right side of the equation and learned again that it's evaluated all as one not left to right ;). Anyways, this way you get a data structure something like this:
# pseudo representation 615 = ( MNH => 36.00 USED => 12.00 PB => 50.00 )
Some examples on how to access it.
keys %data # 614, 615, 616 $data{615} # an anon hashref $data{615}{USED} # 12.00 keys %{ $data{615} } # MNH, USED, PB
Printing out the structure (I've never used DATA::Dumper might it apply here?):
tilly suggested the $h_ref for speed (less hash lookups per inner loop iteration), I'm declaring inside because I'm lazy and don't want to undef it after.for my $key (keys %data) { print "\n$key"; my $h_ref = $data{$key}; printf "\t%s\t%6.2f\n", $_, $h_ref->{$_} for keys %$h_ref; }
It's output:
614 MNH 16.00 USED 32.00 PB 50.00 615 MNH 36.00 USED 12.00 PB 50.00 616 MNH 96.00 USED 2.00 PB 10.00
I didn't do any of the null checks, but that's pretty trivial to add. The \n in the split handles getting rid of the newline.. chomp may be better, I'm not sure.
Just for fun I one lined the db to hash (not exactly efficient):
$data{ (split/\t/)[0] } = { (split/[\t,|\n]/)[1..6] } while <DB>;
Oops, fixed up what Hofmator suggested... I swear I knew that about char classes I just didn't know split well enough and it sort of evolved that way as I worked through ;). Thanks.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: Stuck while learning about the hash
by Hofmator (Curate) on Jun 08, 2001 at 12:46 UTC | |
by hackmare (Pilgrim) on Jun 08, 2001 at 18:41 UTC | |
|
Re: Re: Stuck while learning about the hash
by Stamp_Guy (Monk) on Jun 09, 2001 at 07:11 UTC |