in reply to Re: Hash Splice
in thread Hash Splice

Hi GP,

I really mean "splice" not slice. And I really want to remove 'foo' in initial %hash. Is there a way to do it?

Replies are listed 'Best First'.
Re^3: Hash Splice
by Corion (Patriarch) on Sep 21, 2007 at 09:27 UTC
    use strict; use Data::Dumper; my %h = ( foo => 'bar', baz => 'weeble', ); my @remove = 'baz'; my %removed; @removed{ @remove } = delete @h{ @remove }; print Dumper \%h; print Dumper \%removed;
Re^3: Hash Splice
by perlofwisdom (Pilgrim) on Sep 21, 2007 at 12:49 UTC
    Use the delete function to remove an element from a hash. Example: delete $hash{foo};

    If you only want to remove one of the elements from the anonymous array (say the second element) in the hash element 'foo', you can do this: delete $hash{foo}[1];

    BTW, to keep the values of the hash that you're deleting (in the %wanted hash), the delete function returns the key and value. Example: $wanted{foo} = delete $hash{foo}; Here's a complete example:

    my %wanted = (); my %hash = ( 'foo' => [1,2,3], 'bar' =>[3,4,5]); $wanted{foo} = delete $hash{foo}; print "Left-over:\n"; for $key (keys %hash) { print "$key, @{$hash{$key}}\n"; } print "Wanted:\n"; for $key (keys %wanted) { print "$key, @{$wanted{$key}}\n"; }
    Produces the following output:

    Left-over: bar, 3 4 5 Wanted: foo, 1 2 3
    Good luck!