grep returns all the elements in a list that match a condition, so potentially several elements. You are trying to retrieve a single information (scalar value) from something that can potentially return many, so perl being what it is (it likes to guess what you mean), it guesses that the single information that you want out of that all process is the number of matches.

You should write something like my @stockvals = grep { /a2/ } @array; instead, and check that @stockvals only has one element. Or, if you're really confident, you can write: my ($stockval,) = grep{/a2/} @array;, because of the parentheses the left part is now a list (of only one element, but still a list), and copying a list of data to a list makes sense.

Trying to get a single value is actually called "scalar context", and a list of values "list context". So you can see in grep's documentation that: "In scalar context, returns the number of times the expression was true."

Edit: I answered your specific problem (why isn't grep giving you the value you expect), but I think thanos1983's proposition is a better solution to your overall problem, because once you have filled the hash with the input information, you can easily access any element, while grepping will have to be done for each element on the whole array.


In reply to Re: search and return values from an array by Eily
in thread search and return values from an array by Gtforce

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.