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


In reply to Re: Re: $1 trap by pzbagel
in thread $1 trap by chunlou

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.