in reply to Re: A better understanding of array and hash references
in thread A better understanding of array and hash references
No, you have it backwards. The hash equivalent of
@$ar[0] (or @$ar[0, 1, 2])
is
@$hr{a} (or @$hr{'a', 'b', 'c'})
%$hr{a} is nonsense. Read about slices in perldata
By the way, you shouldn't use slices for single elements.
@$ar[0] and @$hr{a}
should be
$$ar[0] and $$hr{a}
Remember: When using an index on a hash or an array, the sigil is of the type returned/assigned. Slices return/accept a list, so @ is used. When refering to a single element, $ is used. % is never used when an index is specified.
Update: Here's a table which should help:
| Direct | Using References | |||
|---|---|---|---|---|
| Syntax 1* | Syntax 2 | |||
| array | element | $a[0] | ${$ar}[0] | $ar->[0] |
| slice | @a[0,1,2] | @{$ar}[0,1,2] | ||
| unindexed | @a | @{$ar} | ||
| hash | element | $h{'a'} | ${$hr}{'a'} | $hr->{'a'} |
| slice | @h{'a','b','c'} | @{$hr}{'a','b','c'} | ||
| unindexed | %h | %{$hr} | ||
* – The curly brackets around $ar and $hr are optional.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^3: A better understanding of array and hash references
by jeanluca (Deacon) on Dec 02, 2005 at 09:48 UTC |