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; }
In reply to Regular Expression Loop Hell by pjnet
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |