While the above are good answers, there is an ambiguity in the spec. What result would you expect for:

my $left_text = [ qw{ when rome romans} ]; my $right_text = 'When in Rome, Romans do as the Romans do in Rome.';

Would you expect a result of 3 or of 5 (or something else)? Essentially, do you want a count of all case-insensitive matches or just a count of how many search words matched? If you want the latter, the following would suit your purposes better:

#!/usr/bin/perl use strict; use warnings; my @left_text = qw{ when rome romans}; my $right_text = 'When in Rome, Romans do as the Romans do in Rome.'; my $count = '0'; for my $search_text (@left_text) { if ($right_text =~ /\Q$search_text\E/i) { $count++ } } print "Found = $count\n"; __END__ Found = 3

Update: And while you're at it, what do you expect for

my $left_text = [ qw{ when rome romans} ]; my $right_text = 'When in the Terrordrome, do as the Romans.';

If you would only expect 2 matches (ignoring that "rome" is in Terrordrome), then you will want word boundary assertions (\b):

#!/usr/bin/perl use strict; use warnings; my @left_text = qw{ when rome romans}; my $right_text = 'When in the Terrordrome, do as the Romans.'; my $count = '0'; for my $search_text (@left_text) { if ($right_text =~ /\b\Q$search_text\E\b/i) { $count++ } } print "Found = $count\n"; __END__ Found = 2

See perlretut or perlre for more info.


In reply to Re: Regex Find Words by kennethk
in thread Regex Find Words by Xiong

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.