in reply to Re: Hash slices
in thread Hash slices

I tried to find an elegant way to avoid map...grep, but only came up with this:
my %hash2; map { $hash2{$_} = $hash{$_} if /^NETWORK/ } keys %hash;
which is fancy-looking, non-map-in-a-void-context way of saying:
my %hash2; { $hash2{$_} = $hash{$_} if /^NETWORK/ } foreach keys %hash;
My rough check with Benchmark shows no difference between map...grep and map alone until the hash sizes were increased to force memory paging to disk.

[I didn't check to see if anything was optimized away.]

-QM
--
Quantum Mechanics: The dreams stuff is made of

Replies are listed 'Best First'.
Re: Re: Re: Hash slices
by revdiablo (Prior) on Feb 17, 2004 at 22:28 UTC
    I tried to find an elegant way to avoid map...grep

    Roger's first solution actually does this in a pretty nice way. I added some formatting to [hopefully] make it more clear, but here's his code:

    my %hashslice1 = map { /^NETWORK/ ? ($_, $hash{$_}) : ( ) } keys %hash;

    Even still, I can see how mixing the selection of the keys with the hashification is a bit confusing, so that's why I gave a map {} grep {} solution that separates them.

      Thanks!

      Need new glasses (or new eyes).

      -QM
      --
      Quantum Mechanics: The dreams stuff is made of