Solved

Detecting a word from a string in Perl

Posted on 2004-04-29
5
142 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
5 Comments
 
LVL 17

Accepted Solution

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

Expert Comment

by:Zyloch
Comment Utility
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
Comment Utility
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

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

If you get a (Blue Screen of Death), your system writes a small file called a minidump. Your first step is to make certain your computer is setup to record memory dumps. Right click My Computer, choose properties. Click on the advanced tab, an…
This tutorial will discuss the log-in process using WhizBase. In this article I assume you already know HTML. I will write the code using WhizBase Server Pages, so you need to know some basics in WBSP (you might look at some of my other articles abo…
Learn the basics of lists in Python. Lists, as their name suggests, are a means for ordering and storing values. : Lists are declared using brackets; for example: t = [1, 2, 3]: Lists may contain a mix of data types; for example: t = ['string', 1, T…
Learn the basics of while and for loops in Python.  while loops are used for testing while, or until, a condition is met: The structure of a while loop is as follows:     while <condition>:         do something         repeate: The break statement m…

771 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now