The reason your @animals array never changes after the first loop is because the @animals array has changed to the point that it doesn't HAVE the <1> tags in it anymore. If you didn't use a reference to the elements of the array, you'd be fine:
print map( change($_, \@toFind, \@toChange), @animals ); ... sub change { my $str = shift; ... { $str =~ ... } return $str; }
But your loop is dangerous. What if <1>'s "change to" value happens to be this <3> thing? You need to figure out if you want recursive (or chaining) replacements to be allowed. Here's how I'd approach the matter:
# replace($string, \@from, \@to, $allow_recursion) # recursion is turned off by default sub replace { my ($str, $from, $to, $recurse) = @_; # set up a hash for easy lookup my %replace; @replace{@$from} = @$to; # this is the safe way to create a regex # alternation of the possible "from" strings my $from_rx = join '|', map { quotemeta } sort { length($b) <=> length($a) } @$from; # compile the regex $from_rx = qr/($from_rx)/; # this handles non-recursion # as well as recursion... you # might consider this a hack do { $str =~ s/$from_rx/$replace{$1}/g or $recurse = 0; } while $recurse; return $str; }

Jeff japhy Pinyan, P.L., P.M., P.O.D, X.S.: Perl, regex, and perl hacker
How can we ever be the sold short or the cheated, we who for every service have long ago been overpaid? ~~ Meister Eckhart

In reply to Re: Regular Expression Loop Hell by japhy
in thread 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.