How to grep array of arrays
@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 ?
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.
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.
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";
}
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 $_ };
精彩评论