in reply to A better understanding of array and hash references

sorry typo,

@$hr{a}  = ....
should be
%$hr{a} = ....

Replies are listed 'Best First'.
Re^2: A better understanding of array and hash references
by ikegami (Patriarch) on Dec 01, 2005 at 17:32 UTC

    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.

      Very nice table/overview!!!