scope of regexp-match related pseudo variables
In the following:
def foo
p $`, $&, $'
end
def bar x = $`, y = $&, z = $'
p x, y, z
end
'abc' =~ /b/
p $`, $&, $' # => 'a', 'b', 'c'
foo # => nil, nil, nil
bar # => nil, nil, nil
the pseudo variables related to regexp match seem to be reset within foo, and even within the argument receiving part in bar. 开发者_如何学GoI know that this has something to do with scope, but my understanding is that, a variable preceding and outside of a scope can be normally seen from inside that scope (besides some environments related to eval, exec, and the like) even though a variable inside a scope cannot be seen from the outside.
Can you tell me the nature of the scope of these regexp related pseudo variables?
Regexp related pseudo variables don't act like global variables, but are local to the method and thread you're using them in.
I think this is mentioned in "Programming Ruby" - do you have a copy?
To fix your problem: try only passing the values in $backtick
and $&
to foo
and bar
, and if they have an exception, let them raise an exception, and have the calling method handle the exception, log what's in $'
, and then re-raise the exception:
def foo(x, y)
raise if x != "hello"
end
def caller_of_foo
begin
foo($`, $&) # Ignore this comment: `
rescue
STDERR.puts "foo raised #{$!.inspect}"
STDERR.puts "The remainder of the regexp is #{$'.inspect}"
raise
end
end
精彩评论