references

T

toylet

I am studying the examples in the book "Perl 5 by Examples". Here's a
short program from that book:

my $dbf2 = { 3 => { 4=>5, 5=>6 } };
my($key1,$value1,$key2,$value2);
while (($key1,$value1) = each(%{$dbf2})) {
print("level 1: $key1 => $value1\n");
while(($key2,$value2) = each(%{$value1})) {
print("level 2: $key2 => $value2\n");
}
}

The program would prints:

Level 1: 3 => HASH(123456)
Level 2: 4 => 5
Level 2: 5 => 6

Now, what if I create this (which passed the compilation):

my $dbf3 = { { 4=>5, 5=>6} }

How could I make the same program work?
 
C

Charles LaCour

toylet said:
I am studying the examples in the book "Perl 5 by Examples". Here's a
short program from that book:

my $dbf2 = { 3 => { 4=>5, 5=>6 } };
my($key1,$value1,$key2,$value2);
while (($key1,$value1) = each(%{$dbf2})) {
print("level 1: $key1 => $value1\n");
while(($key2,$value2) = each(%{$value1})) {
print("level 2: $key2 => $value2\n");
}
}

The program would prints:

Level 1: 3 => HASH(123456)
Level 2: 4 => 5
Level 2: 5 => 6

Now, what if I create this (which passed the compilation):

my $dbf3 = { { 4=>5, 5=>6} }

How could I make the same program work?
What are you trying to accomplish? In $dbf2 you have a hash that has
one key/value pair. Key name "3" that has a value that is another hash
has 2 key/value pairs. When you defined $dbf3 you have defined a hash
that has a single key/value pair the key is a hash and the value is
undefined.

To better see what data structures you have created try using
Data::Dumper module.
Here is what Dumper gives you for you two hashes:
(This is $dbf2)
$VAR1 = {
'3' => {
'4' => 5,
'5' => 6
}
};

(This is $dbf3)
$VAR1 = {
'HASH(0x8260d54)' => undef
};
 
T

toylet

thank you for the tip on Data::Dumper. I was just testing my skills on
accessing data structures of Perl.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top