in reply to Comparison between a string and an array

Try this
my @answer=( "Bad", "Good", "Not good enough" ); chomp(my $user_answer=<STDIN>); if (grep (/\b$user_answer\b/, @answer)){ print "Ok\n"; }
using regex to match your input with the array elements, it's important to use word boundaries (\b) around the variable or a user input of "Ba" will match "Bad" etc

Replies are listed 'Best First'.
Re^2: Comparison between a string and an array
by Eth443 (Initiate) on May 04, 2015 at 21:09 UTC

    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

      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:  <%-(-(-(-<