develooper Front page | perl.perl5.porters | Postings from December 2011

[perl #105280] wishlist: \$hash{nonexistent} should defer autovivification

Thread Previous | Thread Next
From:
Father Chrysostomos via RT
Date:
December 4, 2011 06:35
Subject:
[perl #105280] wishlist: \$hash{nonexistent} should defer autovivification
Message ID:
rt-3.6.HEAD-5084-1323009348-681.105280-15-0@perl.org
On Sun Dec 04 01:48:20 2011, davidnicol@gmail.com wrote:
> I would like taking a reference to a nonexistent hash element to do
> magic similar to the magic done when a nonexistent hash element is
> used as a function argument.
> 
>    my %hash;
>    my $fancyref = \$hash{doesnotexist};
> 
> at this point, C<keys %hash> would still be empty.
> $fancyref would appear to be undefined, and would evaluate as false.
> ref($fancyref) would be true, like an overloaded object.
> 
> Both of these would remain unchanged
> 
>  perl -le '$r = \$h{k}; $$r=5; print %h'
> k5
>  perl -le '$r = \$h{k}; $h{k}=5; print $$r'
> 5
> 
> except that $r would be false until the key is created in the second
> statement, instead of the key getting created in the first statement.
> 
> C<\$hash{keyname}> would become a concise way to spell
> C<exists($hash{keyname})> with the added feature of providing a
> reference or a delayed reference.
> 
> The autovivification deferral should work with
> nonexistent-hash-element function arguments:
> 
>  {
>     sub reftosecond{ my $r2= \$_[1]; return $r2 }
>     my %h; my $r = reftosecond($h{one}, $h{two});
>     ok ( (!keys %h), "taking reference to nonexistent hash elt arg
> does not create entry");
>     $$r = 27;
>     is( $h{two}, 27, "assigning to deferred hash elt ref creates
> entry");
>     $r = \$h{three};
>     ok( !$r, "reference to nonexistent hash elt is false");
>     $h{three} = 28;
>     is ($$r, 28, "dereferencing reference to formerly nonexistent hash
> elt");
>  }

I think that’s a little too weird and surprising.


-- 

Father Chrysostomos


Thread Previous | Thread Next


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