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

I want to define an anonymous hash by taking a slice of a pre-defined hash. How might I do so?
%parm = ( 1 => 2, 2 => 3, 3 => 4, 4 => 5, 5 => 6 ); # useful for $object = Class::Name->new($x); # where only a subset of %parm is needed $x = { @parm{2..4} }; # fails $x = \@parm{2..4}; # fails $x = { 2 => $parm{2}, # trying to avoid 3 => $parm{3}, 4 => $parm{4} }; use Data::Dumper; print Data::Dumper->Dump([$x],['x']); print $/;

Replies are listed 'Best First'.
Re: creates anonymous hashes with hash slices
by merlyn (Sage) on Aug 03, 2000 at 20:14 UTC
Re: creates anonymous hashes with hash slices
by tye (Sage) on Aug 03, 2000 at 20:54 UTC
    $x= {}; # This line probably optional. @{$x}{2..4}= @parm{2..4};
      Ten out of ten for good answer, but minus one for repeatingt the same data twice literally. :-)
      my @i = (2..4); @$x{@i} = @parm{@i};
          -- Chip Salzenberg, Free-Floating Agent of Chaos
Re: creates anonymous hashes with hash slices
by ar0n (Priest) on Aug 03, 2000 at 20:17 UTC
    I'd try this:
    my $rhash; for my $key (qw(one two three four)) { $rhash->{$key} = $parm{$key}; }
    Of course, you can switch qw(one two three four) with @list_of_keys or (1..6)

    update: <homer_simpson>D'oh</homer_simpson>. The following line is what merlyn was referring to:
    for my $key (@parm{one,two,three,four)}) {
    Which was wrong because that expression returns a list of values corresponding to those keys, while what you want is a list of keys.
    It's fixed now. Thanks merlyn!

    -- ar0n | Just Another Perl Joe

      Hmm. Do you really want to use the values as keys again? @parm{qw(one two three)} is the values associated with the keys of one, two, and three. But then your loop tries to re-use them as a key once again.

      -- Randal L. Schwartz, Perl hacker