MonkeeSage
10/5/2006 11:41:00 PM
David Vallner wrote:
> I also strongly disapprove of the Perl-ish use of global variables that
> get set as a side-effect of a regex match. Notably because that's a)
> relying on a side-effect of a function on b) a global variable. But
> coding everything explicitly is a personal pet peeve of mine.
Hi David,
Ruby embraces the side-effect. This doesn't mean unpredictability as
many functional programmers assume; it means that the conditions which
*always cause the same side-effect* should be incorporated into the
control flow, leading to the same output from the same input, always.
s = 'tree'
if s =~ /(.ree)/
p $1
end
# => "tree"
if s =~ /(free)/
p $1
end
p $1 # => nil
$1 will *always* be non-nil after a grouped match, and nil after a
non-match or an ungrouped match. So the side-effect is fully
predictable.
Regarding global variables; I don't see anything wrong with them *in
concept*; granted you don't always need them, and you can explicitly
pass around a local variable (or use an object attribute like an
instance variable) to get the same effect in most cases, but that is
the same thing *conceptually* as using the global scope to implicity
pass the value. Also, granted that you should not clutter up the global
namespace with a bunch of junk, especially not vast quantities of
large, short-lived data; but the result of a regexp match which is
released after the next match attempt doesn't seem to be in that
category.
But those issues aside, I also favor being explicit for the sake of
clarity.
m = /(.ree)/.match('tree')
if m and m[1]
p m[1]
end
But even then, $1 still gets set. ;)
Regards,
Jordan