develooper Front page | perl.perl5.porters | Postings from July 2001

Re: [ID 20010617.002] local hash assignment leaves created keys in hash

Thread Previous
From:
Abigail
Date:
July 5, 2001 19:26
Subject:
Re: [ID 20010617.002] local hash assignment leaves created keys in hash
Message ID:
20010706022809.28437.qmail@foad.org
On Sun, Jun 17, 2001 at 09:35:20PM -0000, benjamin@cam049102.student.utwente.nl wrote:
> This is a bug report for perl from goldbb2@earthlink.net,
> generated with the help of perlbug 1.28 running under perl 5.00503.
> 
> 
> -----------------------------------------------------------------
> [Please enter your report here]
> 
> If I use local to make an assignment to a previously non-existant
> key of a hash, when the block exits, the key remains.
> 
> #! perl
> { local $hash{foo} = 'bar' }
> print keys(%hash), "\n";
> __END__


That's not a bug. "local" localizes a *value*. You are localizing the
value belonging to the key 'foo' in the %hash array. Since that key/value
pair doesn't exists, Perl will autovivify it for you.

> The above code prints "foo", when it should print nothing.
> A similar situation, with a subroutine call, works properly:
> 
> #! perl
> sub foo { local $_[0] = 'bar' }
> foo $hash{baz};
> print keys(%hash), "\n";
> __END__

Different case. You are passing 'foo' a copy of the value of belonging
to $hash {baz} - which doesn't exists and hence it's "undef". No
autovivification is happening here.

But this autovivifies:

    sub foo { local $_[0] = 'bar' }
    foo @hash {'baz'};
    print keys(%hash), "\n";
    __END__


Abigail

Thread Previous


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About