Your specification is incomplete. What result do you want if the same key appears multiple times in your array? That is something that can't happen with a hash, but it can with your list-as-a-hash.

The complete result of a query for some key would have to be a list of matches. Using map() to generate such a result is reasonable, but let's look at your map again:

map{ /^$key/ and s/^$key//, $_ } grep( /^$key/, @ta))
For one, why do you check for the key with grep() and then again in the map block? One of the tests can go.

Secondly, you are using s/// to change the given array element into just the value. Apart from being ugly, this changes your array @ta, so it wouldn't work again the next time. Print @ta after your code has run to see what I mean. Simply extract the value using regex capture.

Third (as has been noted), you want a semicolon instead of comma to separate the statements in the map block. The map block is evaluated in list context, so the comma is a list operator and map will collect both values. That isn't what you want, and it's the reason you need to select the second element from the result ((...)[1]).

Here is one way to do what you want:

my @ta = ("a x", "b y", "c z", 'b yyy'); my $key = 'b'; my @values = map / (.*)/, grep /^$key /, @ta; print "@values\n";
If you only want the first hit, write
my ( $value) = map ...;
Anno

In reply to Re: map and grep one-liner problem by Anno
in thread map and grep one-liner problem by jeanluca

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.