Solved

Detecting a word from a string in Perl

Posted on 2004-04-29
5
148 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

More Than Just A Video Library

Train for your certification. Learn the latest DevOps tools. Grow your skillset to do better work.

At Linux Academy, we release new training modules every week so you'll always be up to date on the latest tech.

Question has a verified solution.

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

Introduction:   Welcome to my first article ever. To begin with, the reason I write this article.  I participated in a question on Experts Exchange about the start command in Windows and there were some discussion about the usage. The discussio…
Introduction This tutorial will give you a fast look what you can do with WhizBase. I expect you already know how to work with HTML at least, and that you understand the basics of the internet and how the internet works. WhizBase is a server-s…
Learn the basics of modules and packages in Python. Every Python file is a module, ending in the suffix: .py: Modules are a collection of functions and variables.: Packages are a collection of modules.: Module functions and variables are accessed us…
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…

717 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