Beruflich Dokumente
Kultur Dokumente
FilteringvaluesusingPerlgrep
Maven (http://perlmaven.com/advanced-perl-maven-video-course)
1/13
7/5/2016
FilteringvaluesusingPerlgrep
2/13
7/5/2016
FilteringvaluesusingPerlgrep
,
grep (/search/grep)
lter (/search/lter)
List::MoreUtils (/search/List::MoreUtils)
any (/search/any)
<> (/search/<>)
glob (/search/glob)
Prev (/static-and-state-variables-in-perl)
Next (/transforming-a-perl-array-using-map)
The internal grep function
of Perl is a lter. You give it
a list of values and a condition, and it returns a sublist of values that yield true for the given
condition. It is a generalization of the grep or egrep commands we know from UNIX and Linux, but
you don't need to know these commands in order to understand the grep of Perl.
The grep function takes two arguments. A block and a list of values.
For every element of the list, the value is assigned to $_ , the default scalar variable of Perl (/thedefault-variable-of-perl), and then the block is executed. If the return value of the block is false , the
value is discarded. If the block returned true the value from the list is kept as one of the return
values.
Pay attention, there is no comma between the block and the second parameter!
Let's see a few examples for grep:
3/13
7/5/2016
FilteringvaluesusingPerlgrep
This example lters out the les that have been modied within the last year, and only let's through
les that are at least one year old.
http://perlmaven.com/filteringvalueswithperlgrep
4/13
7/5/2016
FilteringvaluesusingPerlgrep
grep on Windows
Windows does not come with a grep utility but you can install one or you can use the same Perl
script as above.
Prev (/static-and-state-variables-in-perl)
Next (/transforming-a-perl-array-using-map)
Written by
Gabor Szabo (https://plus.google.com/102810219707784087582?
rel=author)
Comments
http://perlmaven.com/filteringvalueswithperlgrep
5/13
7/5/2016
FilteringvaluesusingPerlgrep
In the comments, please wrap your code snippets within <pre> </pre> tags and use spaces for
indentation.
25Comments
PerlMaven
Recommend 2
Share
Login
SortbyOldest
Jointhediscussion
ChrisJack 4yearsago
Theproblemwithusinggreptocheckforexistanceisit'snotespeciallyefficient.Iftheelementis
foundnearthebeginning,grepwillstillcontinuetotheend.Afastersolutionwouldstopwhenthe
elementisfound.
1
Reply Share
GaborSzabo
Mod >ChrisJack
4yearsago
Ifreallythatcausessomeslownessinaparticularprogramcanbedeterminedbyusinga
profiler,butthe"any"functionsolvesthisslowness.
Reply Share
LardFarnwell>GaborSzabo 4yearsago
Whatisthis"any"functionyouspeakof?
IfeellikeI'mmissingout:(
Ithoughtthatperlmightoptimizethisoutifit'sinanifstatement.
[EDIT]someresearchherefrom07http://mail.pm.org/pipermail/m...
Ifwelookathttp://rosettacode.org/wiki/Qu...
quick_sort(grep$_<$p,@a),$p,quick_sort(grep$_>=$p,@a)
Thepersonwewrotethismusthavebeenassumingthatgrepwasoptimizinghere
otherwiseitisvery
misleading.Ifnotitwouldbedoublingtheamountofcomparisonsneeded:(.
Reply Share
GaborSzabo
Mod >LardFarnwell
4yearsago
Indeedthatcodecompareseachvaluetwice.Itdoesnotchangethe
complexityofthealgorithmsoitonlymattersifthecomparisonisexpensive.
Reply Share
random.engineer>GaborSzabo 2yearsago
Cantweusefollowingtechniquetofindavalueinalist?Ithinkthisisfasterthanusing
grep.
my@names=qw(FooBarBaz)
my%hash
@hash{@names}=undef
http://perlmaven.com/filteringvalueswithperlgrep
6/13
7/5/2016
FilteringvaluesusingPerlgrep
if(exists$hash{$value}){
#codegoeshere
}
1
Reply Share
GaborSzabo
Mod >random.engineer
2yearsago
Formultiplesearches/lookupitwillbefasterthangrep,butitdoesnotmatter
forsmallarrays.
1
Reply Share
bonnyvora 3yearsago
HiGabor,
Thankyousomuchforthiswonderfulinformativewebsite.
Ihaveonedoubt:
Howtomatchadirectorywithitsname?
Suppose,Iwanttoseeisthereanydirectorywithname"abc".
Itriedthis:
$name="abc"
if(d$file)
{
@files2=grep{/$name/}$file#$fileispointingtocurrentdirectory
}
__________________________________________________________________
Butthisalsomatchesthedirectorywithname"abc"aswellas"abc_99","abc00"etc
Iwanttomatchonlyforabc.
Canyoupleasehelpme?
Reply Share
GaborSzabo
Mod >bonnyvora
3yearsago
Iamnotsurewhydoyouusegrepherewhenyouonlyhaveonevaluetocheck?Whynot
just
if(d$fileand$fileeq$name)
or,ifyou'dliketocheckif$nameisonepartofthepaththen\bcanbeofhelphere:
if(d$fileand$file=~/\b$name\b/)
Thoughifyouhad$name="abc.def"thenthiswouldalsomatch"abcXdef"soyoumightwant
tomakesurenoneoftheregexmetacharactersworksin$name.
Check"perldocfquotemeta"forthis.
Reply Share
Vinod>GaborSzabo 2yearsago
HiGabor,
ihavethefollowingcontentsinarray:
@arr=qw(/tftpboot/:boot/tftpboot/boot:grub/tftpboot/boot/grub:pxegrub)
http://perlmaven.com/filteringvalueswithperlgrep
7/13
7/5/2016
FilteringvaluesusingPerlgrep
@arr=qw(/tftpboot/:boot/tftpboot/boot:grub/tftpboot/boot/grub:pxegrub)
ifilteredthecandidateswhicharenothavingaslash:"/"
@candidateshavingthecontents"bootgrubpxegrub"
nowiwantonlythoseelements/candidateswhichdon'tappearin@arrwithaslash
"/".i.e.,aspertheabovecontentsitshouldbe"pxegrub".
iusedgrephere,butnotgettingthecorrectoutput.
Usingthefollowingapproach:
foreachmy$c(@candidates){
my$pattern='\'.$c
if(grep{$pattern=~$_}@arr){
print"$cisnotrequired\n"
}
esle{
print"$cistherequiredcandidate\n"
}
}
Itsgiving"$cisnotrequired"forallthe@candidates.Plssuggest...
Thanks,
Vinod.
Reply Share
GaborSzabo
Mod >Vinod
2yearsago
probably:
grep{$_=~m{$pattern}}
Reply Share
moshenahmias 3yearsago
Hi,
justreadthisandaftercheckingthecodeinthe"Isthiselementinthearray?"sectionIfoundoutthat
thegrepfunctionreturnsthematchingname(underperl5.14),butyousaythatitreturnsanumber,
whatisgoingonhere?
Reply Share
GaborSzabo
Mod >moshenahmias
3yearsago
HaveyoucopiedtheexampleIhad,orhaveyoutriedtowrite
printgrep{...}?
Inthiscase,grepisinLISTcontextandthusitreturnstherealcontent,andnotthenumberof
elements.
Reply Share
Romina 3yearsago
HelloGabor,
http://perlmaven.com/filteringvalueswithperlgrep
8/13
7/5/2016
FilteringvaluesusingPerlgrep
HelloGabor,
Itriedalottomatcharegexpwithmore"++++"
Ihavethecase:
Lineis****file_size:25time:2013/06/1314:22:16file_name:home/sparse_dir/dir3/file1
delta_size:0itemize_change:>f.st....*****
Lineis****file_size:61time:2013/06/1314:22:16file_name:home/sparse_dir/dir3/file2
delta_size:0itemize_change:>f+++++++*****
Lineis****file_size:4096time:2013/06/1314:22:16file_name:
home/sparse_dir/dir3/test_dir1delta_size:0itemize_change:.d..t....*****
Lineis****file_size:11time:2013/06/1314:22:16file_name:
home/sparse_dir/dir3/test_dir1/file3delta_size:0itemize_change:>f+++++++*****
Lineis****file_size:43time:2013/06/1314:22:16file_name:
home/sparse_dir/dir3/test_dir1/file7delta_size:0itemize_change:>f+++++++*****
seemore
Reply Share
GaborSzabo
Mod >Romina
3yearsago
*means0ormore.+means1ormore,soIguessyouneed\++intheregex,or\+{4,}if
you'dliketomatch4ormore.
Reply Share
Romina>GaborSzabo 3yearsago
Thankyouverymuch.
Itworks:)
Reply Share
Perlito 3yearsago
CanweusegrepintheexamplebelowthisoutputisreturnedbyDumper(Data::Dumper)howdoI
retrievelastname(carmen)andfirstname(luis)??
$var1=bless({'name'=>'firstname'=>'John','lastname'=>'Carmen',....
Reply Share
GaborSzabo
Mod >Perlito
3yearsago
Thisisablessedreferencetoahash.Theclassshouldhavemethodstoretreivelastname
andfirstname.
Reply Share
Perlito>GaborSzabo 3yearsago
Doyouhaveanysimilarexamplepostedsomewhere?Thanks:)
1
http://perlmaven.com/filteringvalueswithperlgrep
Reply Share
9/13
7/5/2016
FilteringvaluesusingPerlgrep
MichaStolarczyk ayearago
Isthereapossibilitytochangeregexineachloopiteration?eg.
grep($_=~/^$unique_f[$k]/,@f)
.Willitlookforappropriateitemsin@farraywhen$kisbeingchanged?
Itdoesn'tseemtoworkformeusingthatpieceofcode.
Reply Share
GaborSzabo
Mod >MichaStolarczyk
ayearago
Whatwasyourfullcode?
Reply Share
MichaStolarczyk>GaborSzabo ayearago
my$aaa=<$fh>;
$aaa=~tr/\>[]'\\\///d;
my@f=split",",$aaa;
my@unique_f=uniq@f;
my$length_f=scalar@f;
print"\n\n\t$filename\nUniqueaa:@unique_f\n\nUniqueaacount:$unique_f_length
for(my$k=0;$k<=$unique_f_length;$k++){
my@foo;
@foo=grep(qr/^$unique_f[$k]/,@f);
my@foo_per;
@foo_per=((length@foo)/$length_f)*100;
print"$unique_f[$k]:@foo_per%\n";
Reply Share
GaborSzabo
Mod >MichaStolarczyk
ayearago
anddoyouhaveusestrictandusewarningsinthiscode?Ithinkyourcode
shouldwork,butifIwereyou,I'dwriteasmall,selfcontainedexemple
(withoutthereadingfromafile)toseehowdoesthiswork.
http://perlmaven.com/filteringvalueswithperlgrep
10/13
7/5/2016
FilteringvaluesusingPerlgrep
(withoutthereadingfromafile)toseehowdoesthiswork.
Reply Share
MichaStolarczyk>GaborSzabo ayearago
Yes,Ihaveusestrictandwarningsinmycode.
IneachiterationIgetsuchawarning:
Useofuninitializedvaluewithin@unique_finregexpcompliationatbottlenecks.p
Reply Share
GaborSzabo
Mod >MichaStolarczyk
ayearago
Itseemstheforloopshasanextraiteration.youprobablyneedtouse<
insteadof<=intheconditionoftheforloop.
Reply Share
MichaStolarczyk>GaborSzabo ayearago
Unfortunatelyit'snotthesolution.Thereisaproblemwith@unique_farray
Reply Share
Gabor provides training and development services. He loves to help people improve their way of
programming. He likes to write automated tests and refactor code.
He runs the Perl Weekly (http://perlweekly.com/) newsletter.
Gabor also runs the Perl Maven site.
Suggest a change
(https://github.com/szabgab/perlmaven.com/tree/main/sites/en/pages//ltering-values-with-perlgrep.txt)
http://perlmaven.com/filteringvalueswithperlgrep
11/13
7/5/2016
FilteringvaluesusingPerlgrep
(http://perlmaven.com/digitalocean)
http://perlmaven.com/filteringvalueswithperlgrep
12/13
7/5/2016
FilteringvaluesusingPerlgrep
Related articles
Scalar and List context in Perl, the size of an array (/scalar-and-list-context-in-perl)
$_ the default variable of Perl (/the-default-variable-of-perl)
English (http://perlmaven.com/ltering-values-with-perl-grep)
( http://he.perlmaven.com/ltering-values-with-perl-grep)
(http://tw.perlmaven.com/ltering-values-with-perl-grep)
(http://cn.perlmaven.com/ltering-values-with-perl-grep)
http://perlmaven.com/filteringvalueswithperlgrep
13/13