Hacker News new | ask | show | jobs
by toolz 3620 days ago
Why do the old match operators now implicitly set a global variable? I feel like in a year I'm going to be debugging some really weird race conditions because of that change and I can't see any value in it...if I want to use the value of a match operator I'll _always_ save it to a local variable.

Can anyone shed any light on this, because my first attempts at grok'ing this change have me really blown away.

3 comments

They have been setting the global variable before. This is not a new behaviour. I think it was to match Perls behaviour iirc
Ahh, thanks for the clarification I had no idea this was old behavior but it looks like the new method might allow them to deprecate what I would consider an anti-feature later.
This is the kind of stuff that is great for shell scripting / one liners. I doubt they are ever going deprecate it. Maybe the best thing is to rewind your mind 30 minutes and pretend you never read about it : )

Example

    ruby -ne 'puts $1 if $_ =~ /^(([\d\.])+)/' < /etc/hosts
I knew things would make sense the more I learned about it. Thanks, TIL. Now I'll pretend I never knew about this so I'm never tempted to abuse it.
Ruby has ALWAYS set certain $global_vars based on a match. This borrowed (directly) something that Perl did/does, as well. This is not a new behavior. See docs: http://ruby-doc.org/core-2.2.3/doc/globals_rdoc.html for "global", "predefined" or "magic" variables. That documentation has existed for many, many versions (not just 2.2.3, per the URL).

If you have issue with this sort of thing, you should go to Elixir. ;)

These globals are thread local and method local, so these are safe from race conditions.

Though, I too had to dig into it the first time I saw use of these special vars to gain confidence that I wasn't introducing a world of pain when we hit load.