From: michael libby Date: 2002-08-10T11:05:26+09:00 Subject: Re: The problem with using $1 in regexps -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Friday 09 August 2002 20:07, Philip Mak wrote: > sub _num_quotes { > $_[0] =~ /^(>+)/; > return length($1); > } >[snip] > 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. The advantage to the OO syntax is that a non-match would raise an error when you tried to call MatchData#size, because you would be trying to send 'size' to nil. Which ain't happenin'. One comment on the Perl, it will return 0 if no argument is passed at all. Probably a situation where an error should be raised-- if you have -w on, at least it will complain about the uninitialized variable in the regex. > 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... The following Ruby code using standad OO is certainly shorter (but only slightly more readable) than your Perl code for the same function (even if you remove the "unnecessary" return and just end with length($1); ) and would have helped you catch the bug in your regex right away. As an added bonus, this sort of code is thread-safe. def _num_quotes(x) /^(>*)/.match(x)[1].size end Perl's (and Ruby's) $digits are globals. Good programmers avoid globals (or at least that's what they tell me ). Of course, you can rewrite the Perl to be shorter and get rid of the $1 at the same time (though, I have no idea if it is using the globals behind the scenes): sub _num_quotes { length(( $_[0] =~ /^(>+)/ )[0]); } (note: the ruby code is still shorter -- i love ruby!) -michael ++++++++++++++++++++++++++++++++++++++++++ Michael C. Libby public key: http://www.ichimunki.com/public_key.txt web site: http://www.ichimunki.com ++++++++++++++++++++++++++++++++++++++++++ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iD8DBQE9VHJt4ClW9KMwqnMRAtr+AJ9+tGT/qX8AaarwseARCS7VXEPYigCeMCLm jF+LG5Avnrc4itBGtoZPL7o= =LZ/7 -----END PGP SIGNATURE-----