On Sun, Mar 25, 2007 at 06:48:02AM +0900, David A. Black wrote:
> On 3/24/07, Brian Candler <B.Candler / pobox.com> wrote:
> >(2) Semantic differences between ruby and apparently similar constructions
> >in other languages. Regexps provide an example; on the surface they look
> >very similar to perl, but underneath there are some important differences
> >you may not discover until it's too late.
> >
> >For instance: in Perl, /^abc$/ matches only the string "abc". This is not
> >true in Ruby (although it *is* a valid regexp). To get the same behaviour 
> >in
> >Ruby, you need to write /\Aabc\z/
> 
> Ha -- talk about nostalgic -- when you wrote "Ruby borrows a lot from
> perl - in my own opinion a little too much" in your previous post, my
> first thought was, "I wonder if that means he's reconciled to the
> anchors thing." :-)  (I guess not :-)

:-)

Well, I think I am, more or less. It's just an example of the kind of
language difference which is more significant than just the name of a
method. It's still fresh in my mind though :-)

"Borrows a little too much from Perl": I was thinking of the global $_
variable, and Kernel#print / Kernel#gets which implicitly use it.

There's one time I use this construct, and that's when running Perl from the
command line to extract values from lines:

$ perl -ne 'print "$1\n" if /foo=(.*)/'

I still automatically use Perl for this. I had in my head that the
equivalent Ruby would be something like:

$ ruby -ne 'puts $1 if /foo=(.*)/ =~ $_'

Given that $_ is invoked explicitly there, you might as well write

$ ruby -ne 'puts $1 if /foo=(.*)/ =~ gets'

and not have the implicit $_ operation at all.

But checking this out, it looks like Ruby has special-cased this:

irb(main):006:0> $_ = "abcdef"
=> "abcdef"
irb(main):007:0> puts "xxx" if /abc/
(irb):7: warning: regex literal in condition
xxx
=> nil
irb(main):008:0> puts "xxx" if /ghi/
(irb):8: warning: regex literal in condition
=> nil

Ugh. So the rule which says "anything which is not 'nil' or 'false' is true"
is broken in this construct, and this is just to make ruby more perlish.

I also find it a bit of a pain that gets follows Perl by reading from all
files listed in ARGV. This means that when you really do want to read from
stdin, and your program uses ARGV for other things, then you have to write
"$stdin.gets"

Regards,

Brian.