in reply to Hash Splice

If you really want to "slice" (not really "splice") your hash then you can:

my %hash = ( 'foo' => [1,2,3], 'bar' =>[3,4,5]); my @wantedKeys = qw(foo); my %wanted; @wanted{@wantedKeys} = @hash{@wantedKeys};

Perl is environmentally friendly - it saves trees

Replies are listed 'Best First'.
Re^2: Hash Splice
by Anonymous Monk on Sep 21, 2007 at 09:23 UTC
    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?
      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;
      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!