We help IT Professionals succeed at work.

Search an array for a certain word phrase (part two)

blnukem
blnukem asked
on
Medium Priority
497 Views
Last Modified: 2010-05-18
I would like to add the ability to search for “variants” of a word in this code. So searching for the word (optimize sales) would also find “optimizing sales” and “optimized sale”.



$SearchFor = "optimize sales";

@Array = qw(access to information that helps them optimizing sales opportunities and stay focused on the right optimized sale in helping companies effectively optimize their sales strategies so that they can optimize sales);

$WordCount = () = "@Array" =~ /$SearchFor/g;

print $WordCount;
Comment
Watch Question

Commented:
Hi,

Hope this is your requirement.

@urarray =();
foreach $key(@Array) {
      if($key =~ m/optimiz(\S+)|sale(\S+)/) {
            push(@urarray,$key);
      }
}

print "Array --> @urarray";

Commented:
slight change from prev post ..
if($key =~ m/optimiz(\S+)|sale(\S+)?/)

Author

Commented:
The  $SearchFor variable word will change so the m/ needs to be applied to the variable.

Commented:

#!/usr/local/bin/perl
#
my $SearchFor = "optimize sales";
my $re = qr/(optimiz|sale)/;

my @Array = qw(access to information that helps them
    optimizing sales opportunities and stay focused on the right
    optimized sale in helping companies effectively optimize
    their sales strategies so that they can optimize sales);
my @a = ();
map { push @a, $_ if $_ =~ /$re/; } @Array;

print "WordCount: $#a (@a)\n";

WordCount: 7 (optimizing sales optimized sale optimize sales optimize sales)
CERTIFIED EXPERT
Most Valuable Expert 2014
Top Expert 2015
Commented:
$SearchFor = qr/optimiz\w+ sales?/;

@Array = qw(access to information that helps them optimizing sales opportunities and stay focused on the right optimized sale in helping companies effectively optimize their sales strategies so that they can optimize sales);

$WordCount = () = "@Array" =~ /$SearchFor/g;

print $WordCount;

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.