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;
}
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.