Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Adding a new element to Hash of Hashes

by Anonymous Monk
on Apr 09, 2013 at 12:54 UTC ( #1027724=perlquestion: print w/ replies, xml ) Need Help??
Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks!
I saw a similar code here that shows very close what I am going through. I need to add an extra element to the array ( id ), but no luck, may be someone here will help me with that.
Here is the code, sample code thanks for someone here, that shows what I am trying to do:
#/usr/bin/perl use strict; use warnings; use Data::Dumper; my $array = [ { 'name' => 'Discount', 'total' => '100 ', 'type' => 'Home', 'id' => '01', }, { 'name' => 'Documents', 'total' => '100 ', 'type' => 'Home', 'id' => '02', }, { 'name' => 'Money', 'total' => '340 ', 'type' => 'Card', 'id' => '03', }, { 'name' => 'State', 'total' => '40 ', 'type' => 'Box', 'id' => '04', }, { 'name' => 'Slice', 'total' => '30 ', 'type' => 'Box', 'id' => '05', }, { 'name' => 'Part', 'total' => '45 ', 'type' => 'Box', 'id' => '06', }, ]; my %hash; $hash{$_->{'type'}}{$_->{'name'}} = $_->{'total'} for @$array; #$hash{$_->{'type'}}{$_->{'name'}}{$_->{'total'}} = $_->{'id'} for @$a +rray; # doesnt work print "Results:\n"; for my $k1 (sort keys %hash) { print " $k1:\n"; for my $k2 (sort keys %{$hash{$k1}}) { print " $k2 - $hash{$k1}{$k2}\n"; } } print "\n\n"; warn Dumper %hash; # This is what I am trying to get out of it: =code Results: Box: id - 06 - Part - 45 id - 05 - Slice - 30 id - 04 - State - 40 Card: id - 03 - Money - 340 Home: id - 01 - Discount - 100 id - 02 - Documents - 100 =cut
Thanks for helping!Home

Comment on Adding a new element to Hash of Hashes
Download Code
Re: Adding a new element to Hash of Hashes
by hdb (Prior) on Apr 09, 2013 at 13:05 UTC

    Your first hash assignment stores a value $_->{'total'} in the hash and the second line (that doesn't work) overwrites it. You need to add another level to your hash:

    my %hash; $hash{$_->{'type'}}{$_->{'name'}}{'total'} = $_->{'total'} for @$array +; $hash{$_->{'type'}}{$_->{'name'}}{'id'} = $_->{'id'} for @$array; print "Results:\n"; for my $k1 (sort keys %hash) { print " $k1:\n"; for my $k2 (sort keys %{$hash{$k1}}) { print " id - $hash{$k1}{$k2}{'id'} - $k2 - $hash{$k1}{$ +k2}{'total'}\n"; } }
      Thanks a lot!! It solved!!!

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1027724]
Approved by 2teez
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (4)
As of 2014-12-22 05:08 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (110 votes), past polls