Solved

Detecting a word from a string in Perl

Posted on 2004-04-29
5
147 Views
Last Modified: 2013-12-25
Detecting a word from a string in Perl

give variable $mysentence = "This house is red and not white";

Need a quick routine to check if a word is present in the variable and flag it if it is...

IE....if the word red is in the sentence then wordflag=1 else wordflag=0

Would also be nice if it could handle any case.

thanks
0
Comment
Question by:webcs
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
5 Comments
 
LVL 17

Accepted Solution

by:
dorward earned 25 total points
ID: 10952153
if ($mysentence =~ /word/) { $wordflag = 1; } else { $wordflag = 0; }
0
 
LVL 36

Expert Comment

by:Zyloch
ID: 10953737
To be even more careful, if you want to test the word case insensitive, do this: [code from dorward above]

if ($mysentence =~ /word/i) {$wordflag=1;} else {$wordflag=0;}

--Zyloch
0
 
LVL 48

Assisted Solution

by:Tintin
Tintin earned 25 total points
ID: 10954375
Depends a little on your definition of a word.  Using 'red' as an example, if you don't want to match partial words like 'hatred', then use the \b to only match words based on word boundaries, eg:

my $word = 'red';
my $wordflag = 0;
$wordflag = 1 if ($mysentence =~ /\b$word\b/i);
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In this tutorial I will show you how to make a simple HTML bar chart with the usage of WhizBase, If you want more information about WhizBase please read my previous articles at http://www.experts-exchange.com/ARTH_5123186.html (http://www.experts-ex…
Active Directory replication delay is the cause to many problems.  Here is a super easy script to force Active Directory replication to all sites with by using an elevated PowerShell command prompt, and a tool to verify your changes.
Learn the basics of if, else, and elif statements in Python 2.7. Use "if" statements to test a specified condition.: The structure of an if statement is as follows: (CODE) Use "else" statements to allow the execution of an alternative, if the …
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

733 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question