[Purdue-pm] Can do better with map somehow?

Dave Jacoby jacoby at purdue.edu
Wed Nov 24 12:40:25 PST 2010


Rick really expanded my knowledge on this one, but it was offline, so 
anyone who might benefit from the response missed it.

First, to clarify my terms. By "map", I meant, "using map {} @something 
rather than using for ( @something ) ". I've done that stuff for ten 
years, and I can do it, but it seems map is much more powerful and concise.

My new solution:

     my $first = {
         'a' => { 'foo' => 1, 'bar' => 'Cheers', },
         'b' => { 'foo' => 3, 'bar' => 'Crow', },
         'c' => { 'foo' => 1, 'bar' => 'Neon Cactus', } } ;
     my $second ;
     %$second =
         map { $_, $first->{ $_ } }
         grep { $first->{ $_ }->{ foo } == 1 } # <-- WOW!
         keys %$first ;
     say Dumper $second ;

I never knew you could do grep like that. I know now.

On 11/24/2010 01:57 PM, Dave jacoby wrote:
> So, I have a function that dumps a DB into a hashref. Assume the dump
> looks like a long version of this.
>
> $VAR1 = {
> 'a' => {
> 'foo' => 1 ,
> 'bar' => 'Cheers' ,
> } ,
> 'b' => {
> 'foo' => 3 ,
> 'bar' => 'Crow' ,
> } ,
> 'c' => {
> 'foo' => 1 ,
> 'bar' => 'Neon Cactus' ,
> } ,
> ...
> }
>
> I would love to have that same hashref, except only containing only
> parts where 'foo' == 1. I can certainly loop it, but I'm learning more
> and more about map and it's finding its way into much more of my code.
>
> my $second ; %$second = map { $_ => $first->{$_} } keys %$first ; gets
> me a full copy, but I can't imagine a way to get grep to work for me and
> sort can just organize 'em. Is there a cool thing I'm missing?
>


-- 
Dave Jacoby                         Address: WSLR S049
Code Maker                          Mail:    jacoby at purdue.edu
Purdue University                   Phone:   765.49.67368


More information about the Purdue-pm mailing list