From: Tanaka Akira Date: 2007-12-22T11:58:03+09:00 Subject: Re: named captures assigning to local variables In article <476C095B.3020107@davidflanagan.com>, David Flanagan writes: > Akr's objection to returning the right-hand side string with this syntax > is that it doesn't allow use in a conditional to test success or > failure. One solution is to raise an exception if no match is found. > On the theory that if you're using this syntax you must be really pretty > sure that there are values to extract from the string. Not strong objection. Consistensy is not a goal in Ruby. > But I might also advocate for dropping both the = and =~ syntaxes for > now and thinking about this some more for Ruby 2.0 Then, named captures needs longer code than numeric captures. if /(.)/ =~ str foo = $1 p foo end v.s. if /(?.)/ =~ str foo = $~[:foo] p foo end It needs 2 more "foo" than numeric captures. So people will be tempted to use numeric captures. But numeric captures are easy to miss, capture number tends to change. I'd like to promote named captures. So I propose shorter notation for assignments to local variables: if /(?.)/ =~ str p foo end The assignment syntax is acceptable for me. (It's 1 byte more shorter than =~.) if /(?.)/ = str p foo end > So this code: > > r = /(?.)(?.)/ > r.match(s) {|data| ...} > > would act like this: > > r.match(s) { |data;foo,bar| > foo = data[:foo] > bar = data[:bar] > ... > } Using Proc#binding? > class Symbol > def ~ > $~[self] > end > end I'm not sure that it is appropriate to dedicate Symbol#~ for Regexp. > Another option: give MatchData a method_missing method so that named > captures can be used as method names: $~.foo would be the same as > $~[:foo]. But MatchData probably already has too many existing method > names to make this viable. I'd like to separate method names of MatchData and local variables. I guess I want to use a local variables such as "names", "size", "length", "begin", etc. > Maybe even simpler, and more in line with existing Perl-style regexp > magic: assign named captures to global variables. For a capture named > foo, set $~foo. Its kind of ugly, but it is consistent. Note that Perl6 can assign captured string to a variable. Apocalypse 5: Pattern Matching - perl6 RFC 112: Assignment within a regex http://dev.perl.org/perl6/doc/design/apo/A05.html -- Tanaka Akira