From: nobu.nokada@... Date: 2002-08-10T22:23:29+09:00 Subject: Re: The problem with using $1 in regexps Hi, At Sat, 10 Aug 2002 10:07:07 +0900, Philip Mak wrote: > sub _num_quotes { > $_[0] =~ /^(>+)/; > return length($1); > } # If you were really made a subroutine, you must not meet the # problem. > 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. Recent versions clear $1 and so on when match failed. $ cat a.rb NUM_QUOTES = /^(>+)/ NUM_QUOTES =~ ">>>a" p $1 NUM_QUOTES =~ "a>>>" p $1 $ ruby-1.6 -v a.rb ruby 1.6.7 (2002-08-01) [i686-linux] ">>>" nil -- Nobu Nakada