prasadbabu has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks

Now i started learning the references in perl and it looks handy in some critical situations in coding.

I have some doubts in references.

print @{[%hash]}

The above coding prints the hash.

But i didn't able to get the concept in this reference.

Please explain me how it works.

Thanks in advance

Prasad

janitored by ybiC: Retitle from "reference" because one-word nodetitles hinder site searching

Replies are listed 'Best First'.
Re: doubts in reference
by ccn (Vicar) on Sep 27, 2004 at 11:39 UTC

    • %hash in list context is evaluated as a list of (key , value) pairs
    • a list in brackets [list] -- is a reference to anonymous array
    • @{} -- is dereference of reference to an array
Re: doubts in reference
by Happy-the-monk (Canon) on Sep 27, 2004 at 11:45 UTC

    ccn told you what it does. But actually what it does is

    print %hash; # prints hash as a list of its keys and values.

    - as in -

    print @{ [ %hash ] } # prints hash as a list of its keys and values.

    [ ... ]    # an array reference is created... and
    @{ ... } # that array reference is de-referenced... it is no more.

    Cheers, Sören

      That's a neat trick you can use for obfu code. do something and then undo it before the statement terminates. Theoretically you could add [] and @{} indefinitely to the outter bounds of the hash and it would still be fine..

Re: doubts in reference
by zejames (Hermit) on Sep 27, 2004 at 11:40 UTC
    update : taken into account davorg's remarks.

    Internally, a hash table can be thought of a sort a "special" list. That means the following hash
    %hash = ('test' => '24', 'blah' => '253');
    can be equivalent to
    @hash = ('test', '24', 'blah', '253');

    BTW, => is equivalent to , here.

    So if you understand that a hash is a special representation for an list, then you expression does the following :
    • Take the array reference corresponding to the hash : %hash
    • Derefence it and print it out.

    That is, you convert an hash to a array using the references.

    HTH

    --
    zejames

      I'm not really sure where slices come into it. I think you may have meant "list" instead of "slice".

      A hash can be created from a list of key/value pairs. And a hash evaluated in list context returns that same list (tho' perhaps in a different order). Slices don't enter into in at all.

      Please be a little more careful with your terminology.

      --
      <http://www.dave.org.uk>

      "The first rule of Perl club is you do not talk about Perl club."
      -- Chip Salzenberg