The first way is straightforward, and probably desirable under many circumstances. The second way is kind of inefficient. In the second method, you're creating an anonymous hash, referred to by a temporary hashref. That hashref is then dereferenced as a hash, and assigned to %h2.

The second way takes an extra step. In the narrow context you've displayed it's completely unneeded. It's less memory and computationally efficient, and arguably less clear to the reader.

However, that's not to say there arent times when an anonymous hashref is useful. Consider the following:

my $href = { FOO => 1, BAR => 2 }; my_sub( $href ); sub my_sub { my $href = shift; # do something with the hash ref... }

In other words, references and anonymous hashes are, theselves, useful. But the way you used them in your second example isn't.

Relevant documentation: perlref, perlreftut, and perldsc.


Dave


In reply to Re: What's the difference between a hash ? by davido
in thread What's the difference between a hash ? by syphilis

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.