coldy has asked for the wisdom of the Perl Monks concerning the following question:

Sorry for the easy question, but I cant work it out. Id like to delete a hash key/value pair from a hash within the subroutine, but have it not deleted globally. Whatever combination I try, it always seems to delete the key/value globally. Any suggestions?

Replies are listed 'Best First'.
Re: delete hash key/value in subroutine
by Lawliet (Curate) on Sep 01, 2008 at 04:43 UTC

    Could we see some code? There are multiple things that could have gone wrong. If you have not already, please use strict; in your script and declare all variables with local scope.

    my %hash = ('key1' => 'v1', 'key2' => 'v2'); del_hash_key(\%hash); sub del_hash_key { my $params = shift; my %hash = %$params; delete $hash{'key1'}; print %hash; # Prints the latter key/value pair print "\n"; } print %hash; # Prints both key/value pairs

    I'm so adjective, I verb nouns!

    chomp; # nom nom nom

Re: delete hash key/value in subroutine
by ikegami (Patriarch) on Sep 01, 2008 at 05:46 UTC
    Lawliet's method (copying the hash) is the only way I can think of meeting your requirements. However, if you'll settle for keeping the key while having its value undefined, you can avoid copying the hash.
    my %hash = ('key1' => 'v1', 'key2' => 'v2'); del_hash_key(\%hash); sub del_hash_key { my $hash = shift; local $hash->{'key1'} = undef; # Until end of scope. print %$hash; # Prints the latter key/value pair print "\n"; } print %hash; # Prints both key/value pairs
Re: delete hash key/value in subroutine
by Anonymous Monk on Sep 01, 2008 at 08:53 UTC
    Id like to delete a hash key/value pair from a hash within the subroutine, but have it not deleted globally. Whatever combination I try, it always seems to delete the key/value globally. Any suggestions?

    Where do you get these ideas (what docs/tutorial are you reading)?

    Here's an example

    my %hash = ( 1 .. 4); my $foo = \%hash; my $bar = \%hash; my $baz = $foo ; foobarbaz(\%hash); sub foobarbaz { my $ref = shift; }
    Many names (references) for it ($foo,$bar,$baz) but just one %hash, it doesn't matter where you modify it (even inside sub foobarbaz).

    I suggest you switch to a book like Beginning Perl by Simon Cozens, Peter Wainwright.
    Beginning Perl is a different kind of Perl book. It's written particularly with the beginning programmer in mind, but it doesn't treat you like an idiot, and experienced programmers will not feel patronised. It covers a lot of ground, from the very basics of programming, right through to developing CGI applications for the web. More importantly, it emphasises good Perl practice, and readable and maintainable code.