FAQ 4.68 Why does passing a subroutine an undefined element in a hash create it?

P

PerlFAQ Server

This is an excerpt from the latest version perlfaq4.pod, which
comes with the standard Perl distribution. These postings aim to
reduce the number of repeated questions as well as allow the community
to review and update the answers. The latest version of the complete
perlfaq is at http://faq.perl.org .

--------------------------------------------------------------------

4.68: Why does passing a subroutine an undefined element in a hash create it?

(contributed by brian d foy)

Are you using a really old version of Perl?

Normally, accessing a hash key's value for a nonexistent key will *not*
create the key.

my %hash = ();
my $value = $hash{ 'foo' };
print "This won't print\n" if exists $hash{ 'foo' };

Passing $hash{ 'foo' } to a subroutine used to be a special case,
though. Since you could assign directly to $_[0], Perl had to be ready
to make that assignment so it created the hash key ahead of time:

my_sub( $hash{ 'foo' } );
print "This will print before 5.004\n" if exists $hash{ 'foo' };

sub my_sub {
# $_[0] = 'bar'; # create hash key in case you do this
1;
}

Since Perl 5.004, however, this situation is a special case and Perl
creates the hash key only when you make the assignment:

my_sub( $hash{ 'foo' } );
print "This will print, even after 5.004\n" if exists $hash{ 'foo' };

sub my_sub {
$_[0] = 'bar';
}

However, if you want the old behavior (and think carefully about that
because it's a weird side effect), you can pass a hash slice instead.
Perl 5.004 didn't make this a special case:

my_sub( @hash{ qw/foo/ } );



--------------------------------------------------------------------

The perlfaq-workers, a group of volunteers, maintain the perlfaq. They
are not necessarily experts in every domain where Perl might show up,
so please include as much information as possible and relevant in any
corrections. The perlfaq-workers also don't have access to every
operating system or platform, so please include relevant details for
corrections to examples that do not work on particular platforms.
Working code is greatly appreciated.

If you'd like to help maintain the perlfaq, see the details in
perlfaq.pod.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,039
Messages
2,570,376
Members
47,027
Latest member
PilarRitch

Latest Threads

Top