in reply to map and grep one-liner problem

TIMTOWDI (I had some time to kill :-)

I assume your 'keys' are unique.*

my @ta = ( 'a x', 'b y', 'c z' ); my $key = 'b'; printf "key=%s, value=%s\n", map split, grep { ! index $_, $key . ' ' +} @ta; printf "key=%s, value=%s\n", $key, ${{ map split, @ta }}{$key};

* If not, the first snippet will select the first hit, while the second will give you the last hit.

Update: I could of course have simplified the second snippet further:

printf "key=%s, value=%s\n", $key, { map split, @ta }->{$key};

Replies are listed 'Best First'.
Re^2: map and grep one-liner problem
by jeanluca (Deacon) on Mar 14, 2007 at 14:18 UTC
    This is really getting close to unreadability :)
    There is one thing in the first printf that I don't understand:  index $_, $key . ' '
    What exactly does the last part do ( . ' ' ), adding a space ? why ?

    LuCa
      What exactly does the last part do ( . ' ' ), adding a space ?

      Yes, that's exactly what it does. Otherwise, as johngg points out above, a search for 'b' will match not just 'b', but also, for example, 'bbking'. And if you look closely at this line in Anno's solution:

      my @values = map / (.*)/, grep /^$key /, @ta;

      you'll see that he does the same thing (note the space after ^$key ?)

        I see! Your one-liners confused me, they are hard to read :)

        Thnx a lot!
        LuCa