My 2-cents worth....
Before I discovered smart matching I used to just loop the array and search for a match.
After reading these answers I thought hey maybe I could use 'join'.
In the code below I have 6 methods including smart match ~~ as proof-of-concept.
I run each of the 6 methods on 3 different match variables.
-- sorry about the golf-style code, it's just how I roll --
my$match,$res;
my@array=("Nice","Bad","Good","Not good enough");
foreach$match("Ba","bad","Bad"){
#method submitted by edimusrex using greb with \b boundaries
if(grep(/\b$match\b/,@array)){$res="y"}else{$res="n"}
print"1: $match : $res\n";
#similar as first method but using ^ start and $ finish matching
if(grep(/^$match$/,@array)){$res="y"}else{$res="n"}
print"2: $match : $res\n";
#smart matching just for POC
if($match~~@array){$res="y"}else{$res="n"}
print"3: $match : $res\n";
#the long method I used to use looping the array
$res="n";
foreach(@array){if($_ eq $match){$res="y"}}
print"4: $match : $res\n";
#joining the array and adding ~ to start and finish as boundaries
if(("~".join("~",@array)."~")=~/~$match~/){$res="y"}else{$res="n"}
print"5: $match : $res\n";
#same as above but using \b boundaries instead of hard-coding ~
if(join("~",@array)=~/\b$match\b/){$res="y"}else{$res="n"}
print"6: $match : $res\n\n";
}
results (perl v5.24.0 on Win7) :
1: Ba : n
2: Ba : n
3: Ba : n
4: Ba : n
5: Ba : n
6: Ba : n
1: bad : n
2: bad : n
3: bad : n
4: bad : n
5: bad : n
6: bad : n
1: Bad : y
2: Bad : y
3: Bad : y
4: Bad : y
5: Bad : y
6: Bad : y
|