Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.

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)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top