From: Tom Gilbert Date: 2002-08-10T10:10:52+09:00 Subject: Re: The problem with using $1 in regexps * Philip Mak (pmak@animeglobe.com) wrote: > sub _num_quotes { > $_[0] =~ /^(>+)/; > return length($1); > } > > See the problem in the above subroutine? (It's Perl, but the $1 > problem applies to Ruby too.) The subroutine is meant to return the > number of '>' marks at the beginning of a line. However, I > (mistakenly) wrote a regular expression that will fail to match if > there are no '>' marks. If it fails to match, I end up returning the > length of an uninitialized variable. This slipped past my unit tests > since in the tests, $1 would always start out undefined. The simple > bug of using /^(>+)/ instead of /^(>*)/ took me a while to track down. > > How would a good programmer avoid this situation? In Ruby, I prefer > the =~ and $1 regexp syntax (rather than the OO one) because it's shorter > to write... Well I'd do: return length($1) if $_[0] =~ /^(>+)/; return 0; # or whatever a failed result should be. I don't know what a "good programmer" would do :) Tom. -- .^. .-------------------------------------------------------. /V\ | Tom Gilbert, London, England | http://linuxbrit.co.uk | /( )\ | Open Source/UNIX consultant | tom@linuxbrit.co.uk | ^^-^^ `-------------------------------------------------------'