Dear Monks

Normally I wouldn't have the problem shown below, but for some reason I like one-liners. Why ? I don't know, maybe because they look cool and make my code unreadable :)

Anyway, what I'm trying to accomplish this time is that I would like to treat an array as if it was a hash. Each array element has a string containing two words (the key and the value)
#! /usr/bin/perl -lw # use strict ; my $key = "b" ; printf "key=%s, value is %s\n", $key, get_value($key) ; sub get_value { my $key = shift ; my @ta = ("a x", "b y", "c z") ; # test array return (map{ /^$key/ and s/^$key//, $_ } grep( /^$key/, @ta))[1] ; }
This works great, but for some reason I don't think I've the best solution, because I have to add (...)[1], around the one-liner in order to get the 'value', which doesn't feel right. Element [0] contains a 1.

Is this the only way, or do I something wrong here ?
What I don't understand too is that when I replace the map expression with
map{ /^$key/ and s/^$key// and print "val=$_\n", $_ }
it doesn't work verywell anymore, I only added a print statement ?

Thnx
LuCa

In reply to 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.