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

I've got a hashref containing keys A through D. I want to pass the values of A and B to a given function like so:
my $returnValue = functionCall({ A => $hashRef->{A}, B => $hashRef->{B}, Foo => 'Bar', });
Now, I know I could just pass it the whole hashref by dereferencing it within the anonymous hashref, but I don't want to do that. (That could also clobber default values that functionCall() would give me.) What I'd love to do is tell the interpreter to create me a set of keys and values from $hashRef with the keys I give it.

Any ideas?

------
/me wants to be the brightest bulb in the chandelier!

Vote paco for President!

Replies are listed 'Best First'.
Re: Hash-slicing question...
by ozone (Friar) on Aug 28, 2001 at 00:34 UTC
    try using 'map':
    my $rv = fc({ map { $_ => $hashRef->{$_} } ('A', 'B', ) }); .....
Re: Hash-slicing question...
by clintp (Curate) on Aug 28, 2001 at 06:25 UTC
    I like ozone's answer because you're not actually asking for a slice of the hash. You want the values and the keys to pass to your function. So you actually want a subset of the original hash. Use map().

    If you just wanted values, you could say:

    @{$hashRef}{qw(A B C D)}
    and that's an honest slice.
Re: Hash-slicing question...
by DBX (Pilgrim) on Aug 29, 2001 at 09:34 UTC
    Another solution is to change how your function call handles defaults. Depending on how you set it up, they won't get clobbered:
    sub functionCall{ my ($hashref) = @_; my %defaults = ( A => 1, D => 4, ); %$hashref = ( %$hashref, %defaults, ); }
    You can change this to true defaults if you switch the order to:
    %$hashref = ( %defaults, %$hashref, );
      That would definitely be a thought, but the functions I'm using are from a set of libraries whose behavior I can't change. *shrugs*

      ------
      /me wants to be the brightest bulb in the chandelier!

      Vote paco for President!