pjnet has asked for the wisdom of the Perl Monks concerning the following question:
I am basically looking for a function that will take 2 lists (call them @a and @b for now) and replace all occurrences of @a in a string ($str) with @b.
Now that may seem simple, but this is done within a loop, so the regular expression keeps getting compiled, providing the same response on each loop. So whatever the first loop returns, the subsequent loops return.
HELP!
You'll see what I mean if you run this code. I have tried everything I can think of. Am I WAY overcomplicating this or is this not as simple as I think?
I have other languages that just have a "replacelist" function - you know... provide a string, with 2 lists, and all occurrences of list1 in string are replaced by list2. Does this exist anywhere?
Code:
#!/usr/bin/perl use strict; my @animals = ( "bear<1>\n", "camel<0> <2>\n", "<2>horse\n", "duck<3>\ +n" ); my @changeTo = ( 'A', 'B', 'C', 'D' ); my @toFind = ( '<0>', '<1>', '<2>', '<3>' ); my $k = 0; while($k < 5) { print map( change(\$_, \@toFind, \@changeTo) , @animals ); my $t = shift(@changeTo); my $r = int(rand(100)); push(@changeTo, $r); print "\n$k:\n" . "@changeTo" . "\n";; $k++; } sub change { my $str = shift; my $toFind = shift; my $changeTo = shift; my @f = @$toFind; my @c = @$changeTo; my $i = 0; foreach my $find (@f) { my $change = $c[$i]; $$str =~ s/$find/$change/gi; $i++; } return $$str; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Regular Expression Loop Hell
by japhy (Canon) on Mar 07, 2006 at 18:29 UTC | |
|
Re: Regular Expression Loop Hell
by duff (Parson) on Mar 07, 2006 at 18:22 UTC | |
by Roy Johnson (Monsignor) on Mar 07, 2006 at 22:32 UTC | |
|
Re: Regular Expression Loop Hell
by QM (Parson) on Mar 07, 2006 at 18:12 UTC | |
|
Re: Regular Expression Loop Hell
by Praveen (Friar) on Mar 08, 2006 at 09:12 UTC | |
by pjnet (Novice) on Mar 08, 2006 at 17:31 UTC |