Perl vs. Ruby RegEx captures

Skip to first unread message

Steve Moon

Jun 23, 2016, 12:07:44 AM6/23/16
to TechValley Ruby Brigade
Great meeting tonight. I'm glad I was able to make it.

Jim - here's a contrived example demonstrating what I was saying about Perl not resetting $1, $2 etc. in loops when you do regex catpures. I'm glad to see that Ruby does clear them...

$ cat sample.txt
foo 12
bar xx
baz 87
$ cat test.rb
while gets
    if /^(\w+)\s(\d\d)/
        puts "#{$1} - #{$2}"
        puts "No Match, so: #{$1} - #{$2}" # the bar xx line

$ ruby test.rb < sample.txt
test.rb:2: warning: regex literal in condition
foo - 12
No Match, so:  -          <—— nothing in $1 or $2
baz - 87
$ cat
while (<>) {
    if (/^(\w+)\s(\d\d)/) {  print "$1 - $2\n" }
    else { print "No Match so: $1 - $2\n" }

$ perl < sample.txt
foo - 12
No Match so: foo - 12           <—— wait, what? bar xx didn’t match…
baz - 87

This bit me hard a long time ago in Perl so scared me off of using $1, $2 style regex captures. Nice to know I can trust them in Ruby!
There's plenty of discussion about this issue out there. For example: provides lots of workarounds. Bottom line I'm doing it wrong in my Perl code above, but it mostly works and fails in a surprising way which makes it a bug in my book.

Thanks Jim for teaching me something new tonight!


Reply all
Reply to author
0 new messages