0

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

DaniCee
  • 2,397
  • 6
  • 36
  • 59
  • 2
    Be under no illusions - if you're iterating a data structure, you've got a loop. There is no solution to this. You cannot loop without looping. You can hide the fact you're doing so behind `map` or `grep` - but you cannot change the need to do so. – Sobrique Aug 27 '15 at 08:35

2 Answers2

2

In 5.20+

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

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

ysth
  • 96,171
  • 6
  • 121
  • 214
1

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

my %subhash = map {
                     $hash{$_} >= 3
                     ? ($_, $hash{$_})
                     : ()
                  } keys %hash;
Jim Davis
  • 5,241
  • 1
  • 26
  • 22