5
my %myHash = (
    key1 => {
        test1 => 1,
        test2 => 2,
    },
    key2 => {
        test1 => 3,
        test2 => 4,
    },
);

my $myRef = $myHash{ "key". ((~~keys %myHash) + 1) } //= {
    test1 => 5,
    test2 => 6,
};    

Humor me and assume the above is actually practical. How is it I can delete this newly created key through the reference?

delete $myRef;

Obviously doesn't work

EDIT: So from zostay I have the following...

sub deleteRef {
    my ( $hash_var, $hash_ref ) = @_;

    for ( keys %$hash_var ) {
        delete $hash_var->{$_} if ($hash_var->{$_} == $hash_ref);
    }
}

Usage:

deleteRef(\%myHash, $myRef);

How's that? Still not recommended?

3 Answers3

3

This will delete every occurrence of $myRef in %myHash:

for my $key (keys %myHash) {
    if ($myHash{$key} == $myRef) {
        delete $myHash{$key};
    }
}

You can use == to test for references using the same memory address.

I think this is a bad idea, but I am humoring you.

zostay
  • 3,985
  • 21
  • 30
  • So I'm using a reference to a hash key to reduce the 'typage' since I am accessing a hash of hash on many lines. What do you think of the subroutine? – Jonathan Walker Sr. Aug 16 '12 at 17:14
  • The sub is fine. I don't recommend doing reference comparisons because such things can almost universally be solved better. However, the definition of "better" is subject for debate and the actual problem you are trying to solve. Without knowing the actual problem, I have no idea what a better solution would be. – zostay Aug 16 '12 at 17:31
1

As it stands you'll have to loop through the hash looking for that ref. Or you could add th key to the data structure for future use.

Bill Ruppert
  • 8,956
  • 7
  • 27
  • 44
0

How are you actually generating the new hash key?

It is bad form to search linearly through all hash values to find a particular reference and bypasses the simple fast access that hashes are supposed to provide.

It would make much more sense to write the equivalent of

my $myKey = "key". ((~~keys %myHash) + 1);
$myHash{$myKey} //= {
    test1 => 5,
    test2 => 6,
};

after which you could just do

delete $myHash{$myKey};

but everything hinges on what you really mean by "key". ((~~keys %myHash) + 1)

Borodin
  • 126,100
  • 9
  • 70
  • 144