Search code examples
perlhashkey

Hash contains a key even though a key was not set


In my code I create a hash and then pass it to a function.

my %profile_hash = ();

getProfileInfo(\%profile_hash, $profile_path);

In the function, I do the following:

sub getProfileInfo{
    my %profile_hash = shift;
    my $profile_path = shift;

    foreach my $key (keys (%profile_hash)){
        print $key;
    }
}

I find that when I print the keys, I get:

HASH(0x1b64448)

Could anyone please tell me why this might be occurring? If I print the keys before I pass it to the function, it is empty as expected.


Solution

  • You need to use a scalar inside your sub to grab the passed hash ref, then defererence it in your loop:

    sub getProfileInfo{
        my $profile_hash_ref = shift;
        my $profile_path = shift;
    
        foreach my $key (keys (%{ $profile_hash_ref })){
            print $key;
        }
    }
    

    Pass by Reference