Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic

Re: $1 trap

by chunlou (Curate)
on Aug 10, 2003 at 18:18 UTC ( #282669=note: print w/replies, xml ) Need Help??

in reply to $1 trap

Thanks for the replies.

Are there modules or debugging techniques that can help track down such a logical $1 error? Consider the code below.

print chg("ctag\n", qr/t(g)/); # print "ctag" "g" =~ /(c)/; print chg("ctag\n", qr/t(g)/); # print "ctag" print chg("ctag\n", qr/t(g)/); # print "ctag" "g" =~ /(g)/; print chg("ctag\n", qr/t(g)/); # print "ctga" sub chg { my ($str, $pat) = @_; $str =~ /$pat/; eval "\$str =~ tr/a$1/$1a/" if $1; return $str; }

The code will work most of the time except when something like "g" =~ /(g)/ occurs. If I'm using someone else's code or even my own (I can't force someone or myself to write bug-free code), since the logical error occurs only once a while and even if it happens it's not necessarily noticeable, when such an error does occur, $1 is probably not the first thing coming to my mind when trying to debug it, especially when there're no warning messages pointing me to it.

Are these similar issues whenever using such global variables as $_?

Update: Maybe I should rephrase my question as not just how to avoid this $1 mistake in the first place but how to pinpoint one afterwards should an error already be happening.

Replies are listed 'Best First'.
Re: Re: $1 trap
by pzbagel (Chaplain) on Aug 11, 2003 at 05:04 UTC

    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.


Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://282669]
and John Coltrane plays...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (4)
As of 2018-05-21 03:56 GMT
Find Nodes?
    Voting Booth?