in reply to Comparison between a string and an array

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

Replies are listed 'Best First'.
Re^2: Comparison between a string and an array
by jdporter (Paladin) on Sep 26, 2016 at 01:55 UTC
    my$match,$res;

    my has higher precedence than comma, so $res is an undeclared variable there. And since you're not using strict, why bother declaring at all?

      I thought my$match,$res; the same as writing

      my$match; my$res;

      I'm just declaring both on one line.
      Anyway it was just a rough (working) code fart. If I was gonna bother with strict then I'd even add the shebang! and a "use warning" , but yeah nah, point taken. I'll leave out the local or global declarations next time to make it more obvious, cheers -SJ-

        my ($match,$res);

        would do what you were trying to do.

        But God demonstrates His own love toward us, in that while we were yet sinners, Christ died for us. Romans 5:8 (NASB)