Chap Harrison wrote:
Hello,
Hello,
I have a hash of hashes, and I'm trying to bulk-assign some key/value
pairs to the referenced hash, using a technique I read on the perlmonks
list (hash slices, see link below). I've never been good at working out
syntax where complex data structures are concerned, and this eludes me
completely. Could someone please help me with the syntax of the
assignment, and retrieval of key/value pairs?
Thanks - I appreciate it!
Chap
*************************
#!/usr/bin/perl -d
use strict;
use warnings;
my %schoolprops;
# +
-------------------------------------------------------------------------
# | %schoolprops - a hash of references to hashes
# |
# | key value hash
# | -----------
-----------------------------------------------------------
# | Adams --> {a => 1, ar => 19, af => 13, aw => 11}
# | Baker --> {b => 2, bq => 20}
# | Charlie --> {c => 3, cc => 33, cu => 38}
# +
-------------------------------------------------------------------------
$schoolprops{Adams} = \{}; # map 'Adams' to a ref to an empty hash
{} *is* a reference to an empty hash, \{} is a reference to a reference
to an empty hash.
my $hashref = $schoolprops{Adams}; # create a ref to a hash.
It doesn't create it, it just copies it.
my @keys = ( 'a', 'ar', 'af', 'aw' );
my @values = ( 1, 19, 13, 11);
#
# The following is trying to assign an array to a "hash slice".
# (courtesy http://www.perlmonks.org/?node_id=4402, who did a simpler
# version that did not involve references.)
#
@{{$hashref}->{...@keys}} = @values; # don't know if this is right
If you change "= \{}" to "= {}" then:
@{ $hashref }{ @keys } = @values;
Otherwise it won't work.
while (my ($k, $v) = each %{$hashref}) { # this is just one of many things
print "$k => $v\n"; # I've tried; this one fails at
runtime.
}
John
--
Those people who think they know everything are a great
annoyance to those of us who do. -- Isaac Asimov
--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/