Well...

my $hash; $hash{foo} = bar;
  • Creates a lexical scalar named $hash
  • Assigns 'bar' to the key 'foo' in the global variable %hash (or, more accurately, %main::hash)

    If you meant:

    my %hash; $hash{foo} = 'bar'; #Versus my $hash = {}; $hash->{foo} = 'bar';

    Then there is still a difference. In the first, you create a lexical hash named %hash, then assign a value to one of it's keys. In the second you create a lexical scalar which contains an anonymous reference to a hash.

    To examine the difference, run this:

    #!/usr/bin/perl use strict; use warnings; use Data::Dumper; print "A lexical hash:\n"; my %hash; $hash{foo} = 'bar'; print Dumper(\%hash); print "A lexical hash *reference*:\n"; my $hash = {}; $hash->{foo} = 'bar'; print Dumper(\$hash);
    Note how the variable in the second case "points to" (is a reference to) the actual hash, while the first case is just the hash. I highly suggest reading up on references, and man perlvar -- the nuances are important and often incredibly useful. ;-)

    radiantmatrix
    require General::Disclaimer;
    "Users are evil. All users are evil. Do not trust them. Perl specifically offers the -T switch because it knows users are evil." - japhy

    In reply to Re^3: when is "my" not necessary? by radiantmatrix
    in thread when is "my" not necessary? by argv

    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.