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

whats the difference between this two lines 2 & 3
my %hash={} $hash{ONE}='malay'; $hash->{TWO}='manab';

Replies are listed 'Best First'.
Re: hash Querry
by psini (Deacon) on Sep 09, 2008 at 13:22 UTC

    Now that you have got the mandatory advices, let's see:

    my %hash={}

    Apart from the missing semicolon at the end of this line, the statement is faulty because you define a hash "%hash" and assign to it a hash reference {}! In order to initialize an empty hash you can simply use my %hash; or my %hash=(); assigning to it an empty list.

    $hash{ONE}='malay';

    This one is good, assigns to the element "ONE" of the hash %hash.

    $hash->{TWO}='manab';

    This one is less good, tries assigning to the element "TWO" of the hash reference $hash which is undefined.

    Rule One: "Do not act incautiously when confronting a little bald wrinkly smiling man."

Re: hash Querry
by svenXY (Deacon) on Sep 09, 2008 at 13:05 UTC
    Hi,
    use strict; is your friend. If you put it in front of your statements, you get something like
    Global symbol "$hash" requires explicit package name at 710071.pl line + 5. BEGIN not safe after errors--compilation aborted at 710071.pl line ...
    This is because the first assignments assigns 'malay' to the hash %hash (with key 'ONE'), whereas the second tries to assign 'manab' to an anonymous hash that is referenced by the reference called $hash (that is not explicitely created and therefore errs with "strict" on).
    That said, the second assignment does not add an key/value pair to your %hash!
    Regards,
    svenXY
Re: hash Querry
by wfsp (Abbot) on Sep 09, 2008 at 13:03 UTC
    Add
    use strict; use warnings;
    to the top of your script and see what happens.

Re: hash Querry
by dHarry (Abbot) on Sep 09, 2008 at 13:06 UTC

    I did:

    Reference found where even-sized list expected at ... Can't use an undefined value as a HASH reference at ...
    :-)