1
@array1 = ('20020701', 'Sending Mail in Perl', 'Philip Yuson');
@array2 = ('20020601', 'Manipulating Dates in Perl', 'Philip Yuson');
@array3 = ('20020501', 'GUI Application for CVS', 'Philip Yuson');

@main = (\@array1, \@array2, \@array3);
use Data::Dumper ;
print Dumper \@main ;
print grep { $_ =~ /Manipulating Dates in Perl/} @main ;

How to make the grep working ?

4 Answers 4

3
print grep { $_->[1] =~ /Manipulating Dates in Perl/} @main ;

If you are just going for flat string comparison, you should use this instead:

print grep { $_->[1] eq 'Manipulating Dates in Perl'} @main ;

The regular expression will match any string that contains the string "Manipulating Dates in Perl".

To explain, $_ will contain an array reference. $_->[1] will dereference the array and obtain the element at index 1.

Sign up to request clarification or add additional context in comments.

2 Comments

prints the arrayref, probably not what is actually wanted (though what is wanted is a mystery)
@ysth: Good point. Yes, this will print the arrayref, but it will grep and print the correct arrayref at least. :)
0

You could stringify the inner array before you match a pattern:

@result = grep { "@$_" =~ /Manipulating Dates in Perl/ } @main;

This could also be a job for the smart match operator:

@result = grep { $_ ~~ /Manipulating Dates in Perl/} @main;

This matches any array reference in @main that has at least one element that matches the given regular expression.

In both cases the output is a list of array references, which might not be what you want to display.

1 Comment

0

Dereference them with map:

grep { $_ =~ /please match/ } map { @{$_} } @arrays

Honestly it looks like you'd rather have hash references:

my @docs = ( 
    {id => '20020701', "title" => 'Sending Mail in Perl',  "author" =. 'Philip Yuson'},
    {id => '20020601', "title" => 'Manipulating Dates in Perl', "author" => 'Philip Yuson'}
);

foreach (grep { $_->{"title"} =~ /Manipulating Dates/ } @docs) {
    print "Got match " . $_->{"id"} . "\n";
}

Comments

0

hope this helps...

use feature 'say';

my @fruit      = ('apples', 'oranges', 'pears', 'bananas', 'grapes');
my @dry_goods  = ('corn meal', 'sugar', 'flour', 'corn flakes');
my @sea_food   = ('flounder', 'lobster', 'baked clams');
my @drinks     = ('apple juice', 'milk', 'coke');

my @groceries  = (\@fruit, \@dry_goods, \@sea_food, \@drinks);

foreach (  map { grep {/apple/} @{$_}  }  @groceries ) { say $_ };

Comments

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.