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

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

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

    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

Site Timeline