in reply to Hash slices

Roger has already provided a few solutions, and QM has a good answer, but here's another:

my %newhash1 = map { $_=>$hash{$_} } grep { /^NETWORK/ } keys %hash;

I'm not sure how all these compare in terms of speed, efficiency, etc. This is just how I'd do it for greatest clarity.

Replies are listed 'Best First'.
Re: Re: Hash slices
by QM (Parson) on Feb 17, 2004 at 21:56 UTC
    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

      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