Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re: Use a hashref as a key in another hashref?

by 2teez (Vicar)
on Jun 05, 2014 at 04:13 UTC ( [id://1088774]=note: print w/replies, xml ) Need Help??


in reply to Use a hashref as a key in another hashref?

hi mwb613,
..Is it possible to use hash reference as a key in another hash reference?..

Ordinarily, maybe not! (But that is a 'white' lie) ;) Until you consider module like Tie::RefHash, which allows you use reference as hash key.

use strict; use warnings; use Data::Dumper; use Tie::RefHash; tie my %h, "Tie::RefHash"; my $key_hash_1 = { 'day' => 1, 'month' => 1, 'year' => 2000, 'hour' => 4, 'minute' => + 44 }; my $key_hash_2 = { 'day' => 1, 'month' => 1, 'year' => 2000, 'hour' => 4, 'minute' => + 45 }; %h = ( $key_hash_1 => { 'burgers_sold' => 5, 'fries_sold' => 3, 'sodas_sold' => 11 }, $key_hash_2 => { 'burgers_sold' => 2, 'fries_sold' => 4, 'sodas_so +ld' => 7 } ); print Dumper( $key_hash_1, $key_hash_2 ); print Dumper( \%h ); for ( keys %h ) { print join ' ' => %{$_}, ' => ', %{ $h{$_} }, $/; }
Output:
$VAR1 = { 'hour' => 4, 'minute' => 44, 'month' => 1, 'day' => 1, 'year' => 2000 }; $VAR2 = { 'hour' => 4, 'minute' => 45, 'month' => 1, 'day' => 1, 'year' => 2000 }; $VAR1 = { 'HASH(0x8e963e0)' => { 'fries_sold' => 3, 'sodas_sold' => 11, 'burgers_sold' => 5 }, 'HASH(0x8eb01d0)' => { 'fries_sold' => 4, 'sodas_sold' => 7, 'burgers_sold' => 2 } }; hour 4 minute 44 month 1 day 1 year 2000 => fries_sold 3 sodas_sold +11 burgers_sold 5 hour 4 minute 45 month 1 day 1 year 2000 => fries_sold 4 sodas_sold +7 burgers_sold 2
Secondly, I think where you are using chains of while loops, a for loop would have been better.

If you tell me, I'll forget.
If you show me, I'll remember.
if you involve me, I'll understand.
--- Author unknown to me

Replies are listed 'Best First'.
Re^2: Use a hashref as a key in another hashref?
by tobyink (Canon) on Jun 05, 2014 at 08:47 UTC

    There's also a Tie::RefHash::Weak on CPAN. (The core module Tie::RefHash treats keys as strong references.)

    use Moops; class Cow :rw { has name => (default => 'Ermintrude') }; say Cow->new->name

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1088774]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others examining the Monastery: (3)
As of 2024-04-20 01:29 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found