Perl Delete Base Key Through Hash Link

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 suppose it's really practical. How can I delete this newly created key via the link?

delete $myRef;

Obviously not working

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);
    }
}

Using:

deleteRef(\%myHash, $myRef);

Like this? Still not recommended?

+5
source share
3 answers

This will remove all cases $myRefin %myHash:

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

You can use ==to check links using the same memory address.

I think this is a bad idea, but I'm fooling you.

+3
source

In its current form, you will have to iterate over the hash, looking for this ref. Or you can add a key to the data structure for future use.

+1

-?

- , .

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

delete $myHash{$myKey};

but it all depends on what you really mean by "key". ((~~keys %myHash) + 1)

0
source

All Articles