Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

search and return values from an array

by Gtforce (Sexton)
on Feb 14, 2018 at 16:30 UTC ( #1209148=perlquestion: print w/replies, xml ) Need Help??
Gtforce has asked for the wisdom of the Perl Monks concerning the following question:

I have an @array where a=stock and b=value.

a1 b1 a2 b2 a3 b3 a5 b5 a4 b4

My objective is to find the stock in the array and get its corresponding value for further printing or processing. When I use something like this:

my $stockval = grep{/a2/} @array;

I get a '1' in my $stockval. I'm guessing that I'm only being told about whether a2 exists in the array or not. What should I be doing to get a2's corresponding value b2 into my $stockval? I realize that this probably a very rookie question (am new to perl). Thanks.

Replies are listed 'Best First'.
Re: search and return values from an array
by Eily (Prior) on Feb 14, 2018 at 16:54 UTC

    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.

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

Re: search and return values from an array
by thanos1983 (Vicar) on Feb 14, 2018 at 16:45 UTC

    Hello Gtforce,

    You can use something like that:

    #!/usr/bin/perl use strict; use warnings; use Data::Dumper; use feature 'say'; my @array = ("a1 b1", "a2 b2", "a3 b3", "a5 b5", "a4 b4"); my %hash; foreach my $element (@array) { my ($key, $value) = split(/ /, $element, 2); $hash{$key} = $value; } print Dumper \%hash; say $hash{'a5'}; __END__ $ perl test.pl $VAR1 = { 'a3' => 'b3', 'a5' => 'b5', 'a4' => 'b4', 'a2' => 'b2', 'a1' => 'b1' }; b5

    What I did above is split each array element based on space between strings. Then simply I used the first element as a key to the hash and the second as the value.

    Update: If you prefer one liner:

    my %hash = map { split( / /, $_, 2 ) } @array;

    Hope this helps, BR.

    Seeking for Perl wisdom...on the process of learning...not there...yet!

      Many thanks, Thanos (runs way faster than what I expected)

        Hello again Gtforce,

        Since you are also interested in speed and resources here is a small Benchmark measurement including three different ways of resolving your problem:

        A minor note here, if you use while loop it is a bit faster than foreach loop but it destroys the array.

        In conclusion on this case map looks to be the best option and it can be put it like this on a function:

        Hope this helps, BR.

        Seeking for Perl wisdom...on the process of learning...not there...yet!
Re: search and return values from an array
by Anonymous Monk on Feb 15, 2018 at 09:27 UTC
    @array = ("a1 b1","a2 b2","a3 b3","a5 b5","a4 b4"); print "product?\n"; chomp($prod = <>); foreach(@array){ @items = split(/ /,$_); if($items[0] eq $prod){ print $items[1]; } }

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1209148]
Approved by Eily
help
Chatterbox?
and the fog begins to lift...

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (2)
As of 2018-07-21 10:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    It has been suggested to rename Perl 6 in order to boost its marketing potential. Which name would you prefer?















    Results (446 votes). Check out past polls.

    Notices?