James Ponder wrote:
> 
> Hi, I'm new to ruby and am coming from a perl background - therefore I
> was hoping to use the perlisms in ruby when it came to regexps.
> 
> Quite often you have an input line, and you want to pull data out from it
> using a regexp.  In perl I would do the following, naming my fields without
> ever using $1, $2, etc.:
> 
>   if (($key, $val) = $var =~ /^(.+)=(.+)$/) {
>     # ...
>   }
> 

Something like this came up before (see [ruby-talk:01871] and 01873)

...
> I thought about doing
> 
>   key, val = var =~ /^(.+)=(.+)$/ && $~[1..-1]
>   if key
>     ...
> 
> but nobody would be able to read my code (besides I started feeling sick)...
> 
> so at the moment I just do:
> 
>   if var =~ /^(.+)=(.+)$/
>     key, val = $1, $2
> 
> but that's no where near as nice as perl's one-liner (and I really hate using
> $1, $2 etc.).  Any ideas?
> 

Some things have to be rethought to be done well in Ruby.
This perlism you seek may not be already so easily available,
but you could make something to assist you in the future...


class Regexp
  def if_match(str="")
    if match(str.to_s)
      yield($~[1..-1])
    end
  end
end



/^(.+)=(.+)$/.if_match(var){|v1, v2| 
  # ....
}


I would prefer saving the regex:

pair_re = /^(.+)=(.+)$/

pair_re.if_match(var){|v1,v2|
  # ....
}

If it matches, it passes the values in and executes the block,
otherwise, the block is skipped.

You can enhance this further, of course :-)


Guy N. Hurst

-- 
HurstLinks Web Development    http://www.hurstlinks.com/
Norfolk, VA  23510            (757)623-9688 FAX 623-0433
PHP/MySQL - Ruby/Perl - HTML/Javascript