hitesh (1) [Avatar] Offline
#1
Hi Andrew,

At the bottom of page 149 of your book is this code snippet:

print "@{$employees{asmith}{children}}
"; #print Amanda Amy

Here is seems $employees{asmith}{children} should resolve to a reference to an array.

But, on page 157 line 14:

@{$employees{$id}}{@field_names} = @fields;

It seems like you are assigning hash slice (values @fields to keys @field_names) pointed to by hash reference $employees{$id} but why the @ sign at the beginning?

Thanks,

Hitesh
jandrew (10) [Avatar] Offline
#2
Re: References in Hash of hashes
Hitesh,

> Hi Andrew,
>
> At the bottom of page 149 of your book is this code snippet:
>
> print "@{$employees{asmith}{children}}
"; #print Amanda Amy
>
> Here is seems $employees{asmith}{children} should resolve to a reference to
> an array.

Exactly right, the @ is dereferencing everything within the following braces
as an array.

> But, on page 157 line 14:
>
> @{$employees{$id}}{@field_names} = @fields;
>
> It seems like you are assigning hash slice (values @fields to keys
> @field_names) pointed to by hash reference $employees{$id} but why the @
> sign at the beginning?

I know, it is a little confusing: see page 73: hash-slices are prefixed with
an @ sign.

Let's look at the code in question again:

@{$employees{$id}}{@field_names} = @fields;

Now, consider a hash-slice of an ordinary hash:

%hash = ();
@keys = ('one', 'two', 'three');
@vals = (1, 2, 3);
@hash{@keys} = @vals; # hash-slice assignment

Now we separate all symbols with a little whitespace:

@ hash { @keys } = @vals

Now, 'hash' can be repaced by anything that resolves to a reference to a
hash (wrapped in curly braces). So, if I have a hashref:

$href = {};

I could do:

@keys = ('one', 'two', 'three');
@vals = (1, 2, 3);
$href = {};
@{$href}{@keys} = @vals;

and now we have a similar construct to the one on p.157 (except that there
the hashref is a value in another hash ... and the hashref is autovivified
(see p146-147)).

Does that help clarify things?

regards,
andrew