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
···
On Friday 09 August 2002 20:07, Philip Mak wrote:
++++++++++++++++++++++++++++++++++++++++++
Michael C. Libby x@ichimunki.com
public key: http://www.ichimunki.com/public_key.txt
web site: http://www.ichimunki.com
++++++++++++++++++++++++++++++++++++++++++