CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
Variable matching in regular expressions

 



The Voices
New User

Nov 21, 2009, 11:41 PM

Post #1 of 3 (631 views)
Variable matching in regular expressions Can't Post

Hi. First, let me apologise if this has already been answered elsewhere, I tried searching but couldn't find what I was trying to do.

I am new to Perl and and am writing a script to substitute strings. My question is this:

How do a substitute a string (e.g. 'bird') as well as it's plural ('birds')? Is it possible in one substitution, or do I need to append an 's' to the search string and repeat the substitution with the new variable?

I have pasted the code snippet in question below.

Thanks in advance.
Scott Smile


Code
my %substitute = { 
somekey => 'somevalue',
anotherkey => 'anothervalue',
}

foreach my $key (keys %substitute) {
my $upper_key = uc($key);
my $upper_value = uc($sub_words{$key});
my $proper_key = ucfirst($key);
my $proper_value = ucfirst($sub_words{$key});
$text =~ s/\s$key\s/ $sub_words{$key} /;
$text =~ s/\s$upper_key\s/ $upper_value /;
$text =~ s/\s$proper_key\s/ $proper_value /;
}



toolic
User

Nov 22, 2009, 5:40 AM

Post #2 of 3 (620 views)
Re: [The Voices] Variable matching in regular expressions [In reply to] Can't Post

The following replaces all instances of 'bird' with 'cat'
and all instances of 'birds' with 'cats':

Code
use strict;    
use warnings;

my $sentence = 'My bird looks like two birds.';
$sentence =~ s/\bbird(s?)\b/cat$1/g;
print $sentence;

__END__
My cat looks like two cats.



The Voices
New User

Nov 22, 2009, 8:56 PM

Post #3 of 3 (602 views)
Re: [toolic] Variable matching in regular expressions [In reply to] Can't Post

That does the trick. Thanks for the help. Smile

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives