Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl hash slice from hash return from function

Tags:

perl

Purely academic question, and I don't see instructions banning them here (although there is no 'academic'-like tag I could find).

If I have an existing hash like the following, I can take a slice(?) of it as shown:

my %hash = (one=>1, two=>2, three=>3, four=>4);
my ($two, $four) = @hash{'two','four'};

Is there a way to do this if the hash is returned from an example function like this?

sub get_number_text
{
    my %hash = (one=>1, two=>2, three=>3, four=>4);
    return %hash;
}

One way that works is:

my ($two, $four) = @{ { get_number_text() } }{'two', 'four'};

As I understand it, function returns a list of hash keys/values, the inner {} creates an anonymous hash/ref, and @{} uses the reference to "cast" it to a list aka a hash slice since Perl knows the ref is a hash. (I was a little surprised that the last bit worked, but more power to Perl, etc.)

But is that the clearest way to write that admittedly strange access in one expression?

like image 700
simpleuser Avatar asked Jan 08 '13 22:01

simpleuser


1 Answers

In general, avoid returning a flattened hash (return %foo) from a subroutine; it makes it harder to work with without copying it into another hash. Better to return a hash reference (return \%foo).

But yes, that is the clearest way. Though often lists of hardcoded keys are given using qw:

my ($two, $four) = @{ { returnit() } }{ qw/two four/ };
like image 63
ysth Avatar answered Sep 21 '22 08:09

ysth