Not to sound facetious, but several other posters and I basically answered this question(which is almost identical to your original post) by saying: "Don't do that!" I know it's Perl and TIMTOWTDI, but sometimes the way you are doing it is wrong. Yet again the correct way to write the sub above is:
sub chg {
my ($str, $pat) = @_;
eval "\$str =~ tr/a$1/$1a/" if $str =~ /$pat/;
return $str;
}
As far as debugging other people's code which is coded like this. I suppose firing up the perl debugger and stepping through the program may shed some light, although something as obscure as your example which only fails with some singularly weird input may be very difficult to figure out. However, if you just shuffle around your house hitting yourself in the head with your Camel book and repeating the mantra, "Never check $1 blindly, make certain my regex succeeded." You will, after much meditation and contemplation, literally "beat" it into your head so whenever you see $1 in someone's code, you will instantly make sure it is properly initialized before it is used.
HTH
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|