in reply to Re^2: Comparison between a string and an array
in thread Comparison between a string and an array

I was meaning that with out the \b (to escape word boundaries) "Ba" would match Bad meaning


$match = 'Ba'; @array = ('Bad','Good','Whatever'); if (grep(/$match/, @array)) { print "Yippie!\n"; } else { print "No Match\n"; }

If you enclosed the variable $match in word boundaries as followed

grep(/\b$match\b/, @array)

It would no longer match do to the fact that the match must match the exact string passed

Replies are listed 'Best First'.
Re^4: Comparison between a string and an array
by AnomalousMonk (Archbishop) on May 05, 2015 at 17:24 UTC
    It would no longer match do to the fact that the match must match the exact string passed

    But the  \b assertion does not require an "exact" match, as I understand the term, but rather the presence of a word boundary (based on the  \w character class). So you can have the following "exact" match with 'Ba':

    c:\@Work\Perl\monks>perl -wMstrict -le "use List::MoreUtils qw(any); ;; my $match = 'Ba'; my @array = ('Ba Ba Black Sheep'); ;; print 'exact match?' if any { /\b$match\b/ } @array; " exact match?
    See Assertions.


    Give a man a fish:  <%-(-(-(-<

      You're right.

      The better way to write it would probably be:

      my $match = 'Ba'; my @array = ('Ba Ba Black Sheep'); if (grep(/^$match$/,@array)) { print 'exact match?'; } else { print "No match\n"; }