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 |