DaniCee
DaniCee

Reputation: 3207

Perl: Is it possible to subset a hash passing a value threshold?

Say I have a hash of the form:

%hash = ( a => 1, b => 2, c => 3 , d => 4 , e => 5 , f => 6 );

Can I obtain a subset of such hash passing a value threshold of 3, obtaining the following %subhash

%subhash = ( c => 3 , d => 4 , e => 5 , f => 6 );

and without having to enter a loop? Thanks

Upvotes: 0

Views: 148

Answers (2)

ysth
ysth

Reputation: 98398

In 5.20+

%subhash = %hash{ grep $hash{$_} >= 3, keys %hash }

(though grep (and map) is still a loop)

Upvotes: 2

Jim Davis
Jim Davis

Reputation: 5290

Something like this should do it, although a map implies a loop:

my %subhash = map {
                     $hash{$_} >= 3
                     ? ($_, $hash{$_})
                     : ()
                  } keys %hash;

Upvotes: 1

Related Questions