Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: Chaining string ops

by fletcher_the_dog (Friar)
on Aug 28, 2003 at 18:04 UTC ( [id://287474]=note: print w/replies, xml ) Need Help??


in reply to Chaining string ops

Here is a way you could encapsulate the chaining in a subroutine
use strict; my $str = "the boy walked the dog"; $str=ChainSubs($str, walked=>'fed', boy=>'girl', dog=>'Audrey II' ); print $str; sub ChainSubs{ my ($string,%subs)=@_; foreach my $original (keys %subs) { $string=~s/$original/$subs{$original}/; } $string; }
This of course assumes that you don't care what order the substitutions are done in. If you did care, you could walk through @_ two elements at a time like this:
sub ChainSubs{ my $string = shift; for (my $i=0;$i<@_;$i+=2) { $string=~s/$_[$i]/$_[$i+1]/g; } return $string; }

Replies are listed 'Best First'.
Re^2: Chaining string ops
by Aristotle (Chancellor) on Aug 28, 2003 at 18:11 UTC
    Using splice is easier than doing it with for(;;).
    sub ChainSubs{ local $_ = shift; while(@_) { my ($s, $t) = splice @_, 0, 2; s/$s/$t/g; } return $_; }

    Makeshifts last the longest.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://287474]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (4)
As of 2024-04-25 13:27 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found