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

I tried putting Ba and doesn't match as you said, actually for me it's working, but I will considere your answer/reflexion for future codes. Thanks

  • Comment on Re^2: Comparison between a string and an array

Replies are listed 'Best First'.
Re^3: Comparison between a string and an array
by edimusrex (Monk) on May 05, 2015 at 14:26 UTC
    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

      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"; }