Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl Delete Base Key through Hash Reference

Tags:

perl

perl-hash

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?

like image 230
Jonathan Walker Sr. Avatar asked Oct 07 '22 22:10

Jonathan Walker Sr.


2 Answers

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.

like image 121
zostay Avatar answered Oct 10 '22 21:10

zostay


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.

like image 44
Bill Ruppert Avatar answered Oct 10 '22 21:10

Bill Ruppert