Solved

Detecting a word from a string in Perl

Posted on 2004-04-29
5
146 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
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: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

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 aim to show you how simple is making a small application in WhizBase, how to add, remove and update data in the DB. I will make a small address book application where you can add, browse, update and remove addresses. I wi…
This tutorial will discuss fancy secure registration forms, with AJAX technology support. In this article I assume you already know HTML and some JS. I will write the code using WhizBase Server Pages, so you need to know some basics in WBSP (you mig…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

856 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