0

How do I grep values from an array of arrays? My attempt:

my $match =grep (/value/, @array);

if ( $match <= 0 ) { ... }

I am always getting zero as a output which is incorrect.

I am able to print $value after 2 for, loops so I think grep will only work when there is 1 loop.

for $value (array) {
    for my $value1 (@$value) 
    { print $value1 }; 

Thanks.

9
  • grep returns a list. If you assign it to a scalar, you will get the length of the list. Commented Jul 7, 2014 at 15:09
  • That being said, are you saying that you wish to grep vales from a list of lists? Commented Jul 7, 2014 at 15:10
  • Please ignore Len Jaffe's first comment. grep does not return a list in scalar context (e.g. when assigning its result to a scalar). It would crash the program if it tried. Commented Jul 7, 2014 at 15:14
  • Please ignore Len Jaffe's second comment. There's no such thing as a list of lists. You were correct when you said array of array. Commented Jul 7, 2014 at 15:16
  • "Evaluates the BLOCK or EXPR for each element of LIST (locally setting $_ to each element) and returns the list value consisting of those elements for which the expression evaluated to true. In scalar context, returns the number of times the expression was true." How is that substantially different from what I said? Commented Jul 7, 2014 at 15:46

1 Answer 1

1

To grep first level of arrays into @result

my @result = grep { grep { /search/ } @$_ } @array;

grepping final strings into @result,

my @result = grep { /search/ } map { @$_ } @array;
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks , so shall I use second level answer as I am looking for answer in 0 or 1 ..Like if I grep something and if value is blank then I shouldn't process. if (@result) { found value } else { array is empty }... I am correct

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.