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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.