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

I have a function that returns a hash reference. I want to get a slice of the returned hash reference without using a temporary variable. But it seems to be very tricky. This does not work:

sub x { return {qw(a b c d)}; } print @{%{x()}}->{"a","b"};

While this does:

sub x { return {qw(a b c d)}; } print %{x()}->{"a"};
How would I get a slice?

Replies are listed 'Best First'.
Re: How to get a slice of hash ref that a sub returns.
by TheHobbit (Pilgrim) on Apr 18, 2002 at 22:21 UTC

    Hi,
    Simple, make it simple...

    sub x {return {a => 1, b=> 2, c => 3}} print @{x()}{a,b}
    does the job.

    Cheers
    Leo TheHobbit
    GED/CS d? s-:++ a+ C++ UL+++ P+++>+++++ E+ W++ N+ o K? !w O? M V PS+++
    PE-- Y+ PPG+ t++ 5? X-- R+ tv+ b+++ DI? D G++ e*(++++) h r++ y+++(*)
Re: How to get a slice of hash ref that a sub returns.
by dmitri (Priest) on Apr 18, 2002 at 21:48 UTC
    OK, I got it (after I tried several million things):

    sub x { return {qw(a b c d)}; } print @{%{x()}}{"a","c"};

    The trick was to kill the arrow (even though I am not yet sure why).

      You can drop the %{}:

      sub x { return {qw(a b c d)}; } print @{x()}{"a","c"};
      I find that references quick reference makes this stuff easy to remember.

              - tye (but my friends call me "Tye")