Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses

Re: search and return values from an array

by Eily (Prior)
on Feb 14, 2018 at 16:54 UTC ( #1209152=note: print w/replies, xml ) Need Help??

in reply to search and return values from an array

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.

Replies are listed 'Best First'.
Re^2: search and return values from an array
by Gtforce (Sexton) on Feb 14, 2018 at 18:43 UTC

    Eily - I should have used @stockvals as opposed to attempting to stuff it into a scalar, thanks.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1209152]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (8)
As of 2018-08-18 17:55 GMT
Find Nodes?
    Voting Booth?
    Asked to put a square peg in a round hole, I would:

    Results (185 votes). Check out past polls.