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: Re: [rovf] Substitutions: Edit Log



BillKSmith
Veteran

Feb 13, 2013, 10:04 AM


Views: 852
Re: [rovf] Substitutions

It is not necessary to split the text. Use the /e option to evaluate the hash in the replacement field of the substitution.

Code
use strict; 
use warnings;
my %number = (
one => 1,
two => 2,
three => 3,
);

while (my $line = <DATA>) {
$line =~ s/(:?one|two|three)/$number{lc $1}/egi;
print $line, "\n";
}
__DATA__
John has three apples, two cats and one girlfriend

Ouput:

Code
John has 3 apples, 2 cats and 1 girlfriend


EDIT: Minor correction to make code case insensitive.
Good Luck,
Bill

(This post was edited by BillKSmith on Feb 13, 2013, 10:18 AM)


Edit Log:
Post edited by BillKSmith (Veteran) on Feb 13, 2013, 10:18 AM


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

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