regex - Perl Grepping from an Array -
i need grep value array. example have values
@a=('branches/soft/a.txt', 'branches/soft/h.cpp', branches/main/utils.pl'); @array = ('branches/soft/a.txt', 'branches/soft/h.cpp', branches/main/utils.pl','branches/soft/b2/c.tct', 'branches/docs/a1/b.txt');
now, need loop @a , find each value matches @array. example
it works me grep. you'd exact same way in more::listutils example below, except having grep instead of any. can shorten
$got_it = grep { /$str/ } @paths; @matches = grep { /$str/ } @paths; this default tests /m against $_, each element of list in turn. $str , @paths same below.
you can use module more::listutils well. function any returns true/false depending on whether condition in block satisfied any element in list, ie. whether there match in case.
use warnings; use strict; use most::listutils; $str = 'branches/soft/a.txt'; @paths = ('branches/soft/a.txt', 'branches/soft/b.txt', 'branches/docs/a1/b.txt', 'branches/soft/b2/c.tct'); $got_match = { $_ =~ m/$str/ } @paths; with list above, containing $str, $got_match 1.
or can roll hand , catch match well
foreach $p (@paths) { print "found it: $1\n" if $p =~ m/($str)/; } this print out match.
note strings show in example do not contain 1 match. added list test. without in list no match found in either of examples.
to test more 1 string, added sample
my @strings = ('branches/soft/a.txt', 'branches/soft/h.cpp', 'branches/main/utils.pl'); @paths = ('branches/soft/a.txt', 'branches/soft/h.cpp', 'branches/main/utils.pl', 'branches/soft/b2/c.tct', 'branches/docs/a1/b.txt'); foreach $str (@strings) { foreach $p (@paths) { print "found it: $1\n" if $p =~ m/($str)/; } # or, instead of foreach loop above use # $match = grep { /$str/ } @paths; # print "matched $str\n" if $match; } this prints
found it: branches/soft/a.txt found it: branches/soft/h.cpp found it: branches/main/utils.pl
when lines grep uncommented , foreach ones commented out corresponding prints same strings.
Comments
Post a Comment