Ex-Perl coders: Howz it feel to convert to Ruby?

Or in irb:
  > Array.methods.sort
=> ["&", "*", "+", "-", "<<", "<=>", "==", "===", "=~", "", "=",
"__id__", "__send__", "all?", "any?", "assoc", "at", "class",
"clear",
"clone", "collect", "collect!", "compact", "compact!", "concat",
"delete",
"delete_at", "delete_if", "detect", "display", "dup", "each",
"each_index", "each_with_index", "empty?", "entries", "eql?",
"equal?",
"extend", "fetch", "fill", "find", "find_all", "first", "flatten",
"flatten!", "freeze", "frozen?", "grep", "hash", "id", "include?",
"index", "indexes", "indices", "inject", "insert", "inspect",
"instance_eval", "instance_of?", "instance_variable_get",
"instance_variable_set", "instance_variables", "is_a?", "join",
"kind_of?", "last", "length", "map", "map!", "max", "member?",
"method",
"methods", "min", "nil?", "nitems", "object_id", "pack", "partition",

"pop", "private_methods", "protected_methods", "public_methods",
"push",
"rassoc", "reject", "reject!", "replace", "respond_to?", "reverse",
"reverse!", "reverse_each", "rindex", "select", "send", "shift",
"singleton_methods", "size", "slice", "slice!", "sort", "sort!",
"sort_by", "taint", "tainted?", "to_a", "to_ary", "to_s",
"transpose",
"type", "uniq", "uniq!", "unshift", "untaint", "values_at", "zip",
"|"]

It may not give you all the information about each method, but you
can
often get a pretty good idea from the name - if not, then you can use
ri
to figure it out.

This is one of those situations where I kinda miss Python and its
ability to store and later display the docstring of a function or class
when requested.

One thing at a time, I suppose.

-- Brian Wisti

Brian Wisti wrote:

Hmm ... TMTOWTDI applies in both Perl and Ruby. I think I would have
written most of your examples differently, and that difference is
probably why Perl<->Ruby isn't a big deal for me.

(1) The complete OO nature of Ruby IMO changes everything. Perl is still procedural in it's basic constructs. To iterate from 1 to 10
in Perl can be shortened *somewhat* from say C or Java using this
construct:

for (0..9) { do_somthing_with( $_ ) }

  foreach my $i (0..9) { do_something_with($i) }

You know, a stylistic thing for sure, but I've stopped using "foreach" and just use "for" everywhere. And if I can get away with using $_, I do in lieu of the "my $i" unless I have inner loops and I need a variable to ferret out abiguity. But I'm OT here, discussing Perl sytle in a Ruby NG.

or even

  map { do_something_with($_) } (0..9);

10.times { |i| do_something_with( i ) }

  0.upto(9) { |i| do_something_with(i) }

To me, this is a significant difference and I think this gets
magnified the deeper one goes into Ruby.

True enough, but presumably your understanding deepends as you go
deeper into Ruby, yes?

I would agree with that.

(2) I think the need to be familiar with the class methods and properties is magnified in Ruby. This is similiar to C++ where it's difficult to be productive unless one gains experience in the classes

and methods available. In Perl, this is not as much the case, again
do to the fact you can go completely procedural in Perl and get away
with it. If you do use OO and modules in Perl, then you only need to know

the methods for the module you imported and the rest can be
procedural in Perl. In Ruby, it seems you can't really get away with that it
seems.

Sure, but POLS is a decent guideline, and when all else fails I call
obj.methods() from irb to see what I get to play with. I generally
don't need to refer to docs for libraries that I haven't imported, so
I'm not sure I understand that bit.

irb is nice just as "perl -e" on the command line is for checking out features. I've done both as well as "ruby -e".

And maybe things aren't as straightforward in Perl as you describe. One
still has to be familiar with the full standard library, the various
sigils, the built-in types, and all of the modules that you've
imported.

I can't argue too much that Perl is kind of it's own thing too, yes. But it's still easy to keep completely procedural and I would say a large amount of Perl that I see is.

(3) Another contrived example, this time in Ruby:

def Contrived
   3.times { yield }
end

[ "tic", "tac", "toe" ].each do |item|
   Contrived { printf "%s ", item }
   printf "\n"
end

There is a lot about this that is different than Perl IMO. I could create an anonymous subroutine in Perl to function something like the

yield block, and I realize the Ruby above is itself somewhat
contrived, but... still, you wouldn't normally do something like this in Perl whereas in Ruby, these sorts of things are actually useful.

Useful, sure. Widely used, you betcha. Fact is that I've still never
needed to use yield in any production code. Use what you need, not what
you feel like you're supposed to. Your sample Perl code didn't show
taint-checking or full conformance to strict and warnings, even though
that is widely promoted as the "right way" to do things.

(4) Each language has it's own strengths. IMO one of Perl's
strengths is the simplicity and consistency of it's parameter passing:

sub shell {

   my @output;
   for (@_) { push @output, `$_` }
   chomp( @output );
   return wantarray ? @output : \@output;

}

## My favorite "Rubyism" I use all the time in Perl -- puts()!

sub puts { for (@_) { print "$_\n" } }

puts( shell(
   "ls -l",
   "ps -ef | grep -i foo",
   "rm *.bar",
));

Yup, it's a strength of Perl, and that's a nifty puts subroutine :slight_smile:

Thanks. It's tremendously useful for a ton of things written this way. I still find uses for it that surprise and delight, not to mention that I have "puts()" in every language I use -- C, JavaScript, Perl, VB, WSH, etc. I don't even have to remember any more, except I can't do the above (with the array as a parameter) in anything but Perl.

So the point is I don't want to approach Ruby as Perl even though
there are similiarities. Unfortunately, I see most people approach Perl in

the same way as C and Java and JavaScript and Perl really looses it's

benefits quickly when approached in this way. I don't want to do the

same with Ruby.

What's wrong with taking advantage of the languages that Ruby builds
on? Familiarity with Perl, Python, Smalltalk, and LISP are all
incredibly useful with Ruby, and sometimes a design is easiest to
express in something resembling one of those languages.

I can see a problem with trying to make your Ruby code look *exactly*
like Perl code, same as writing a C-style for(;:wink: loop instead of a
for/foreach loop in Perl is ugly. But hey, sometimes it's useful. I
don't knock what works, as long as I can read it :slight_smile:

Perhaps these weak examples answer your question. And so the
original question, clarified more (more muddied more as the case may be), remains... Howz it feel to convert to Ruby _really_ and not just applying the "Perl" mindset to Ruby, which I think is a mistake. It's clear from even the basic constructs it isn't the same.

Sure, it's not the same. But insisting on doing things the "Ruby Way"
immediately is naturally going to result in a serious dip in
productivity compared to going out and writing code that works, right
away.

This is a perspective I need to adopt more, for sure. It's probably the only realistic way and was exactly the same way I learned Perl. I didn't develop that puts() call above overnight, as simple as it is, simply because my ability to conceptualize it that easily didn't exist until after I had written a significant amount of code. The same will be true for Ruby.

-ceo

David A. Black wrote:

Hi --

(3) Another contrived example, this time in Ruby:

def Contrived
   3.times { yield }
end

[ "tic", "tac", "toe" ].each do |item|
   Contrived { printf "%s ", item }
   printf "\n"
end

There is a lot about this that is different than Perl IMO. I could create an anonymous subroutine in Perl to function something like the yield block, and I realize the Ruby above is itself somewhat contrived, but... still, you wouldn't normally do something like this in Perl whereas in Ruby, these sorts of things are actually useful.

Well, I would do:

  puts ["tic", "tac", "toe"]

or

  puts %w{ tic tac toe }

but I know you meant it just as an illustration of yield :slight_smile:

Yep!

(But

still it's always a pleasure to see how compact and clean Ruby can
be.)

Yep (again).

## My favorite "Rubyism" I use all the time in Perl -- puts()!

sub puts { for (@_) { print "$_\n" } }

A perhaps slightly pedantic point: this isn't what puts actually does.
It adds a "\n" to the end of the string only if one isn't there
already.

You know, I didn't discover that until this week on my re-entry into Ruby... But I'd say 95% of the time I use puts in Ruby, it's without the "\n" at the end, so in Perl I like having the same behavior.

-ceo

···

On Thu, 16 Sep 2004, Chris wrote:

Phil Tomson wrote:

In article <8x%1d.2604$Qv5.529@newssvr33.news.prodigy.com>,

(4) Each language has it's own strengths. IMO one of Perl's strengths is the simplicity and consistency of it's parameter passing:

sub shell {

  my @output;
  for (@_) { push @output, `$_` }
  chomp( @output );
  return wantarray ? @output : \@output;

}

Actually, I think this is one of the _worst_ things about Perl and it was one of those nagging little annoyances that when added up finally led me to seek out alternatives. The problem with the way parameters are passed to subroutines in Perl is that you can't tell from a glance how many params are supposed to be passed into the subroutine and you have no information about what the params are. You've got to look down through the subroutine code to see if there's a 'shift @_' lurking somewhere in the code (for the uninitiated, you pass params to Perl subroutines via the '@_' global list; you have to 'manually' shift the params off of that list - blech! )

An incredibly interesting point of view though your justification for it is somewhat understandable. Pathological mistakes can occur this way for those that use this, what I would call an incredibly nice feature, in an undisciplined way. I'm quite disciplined about spiking out my arguments in Perl at the top of a subroutine. I think your dislike perhaps has been fueled by people that write subroutines in a "hackish" sort of way. (I would imagine "hacking" Ruby is just as possible to accomplish.)

But aside from the undisciplined uses you've pointed out as reason for eshewing this in Perl, I have to wholy stand by the amazing power this feature brings. It far outweighs the negatives. It's one of the "genius" things about Perl. (Always educational, however, to get someone else's opposite point of view, as you have offered.)

And to bring this Perl discussion back on topic, in line with your dislike of this "feature" in Perl, am I not correct in understanding that in Ruby, one can create methods on the fly in a class? How is this that much different (conceptually) than unspecified parameters in a Perl subroutine? How do you know what methods are there (aside from using the inspection methods available to every class [unless I am mistaken in this regard]).

-ceo

···

Chris <ceo@nospan.on.net> wrote:

Bill Kelly wrote:

Hi,

From: "Chris" <ceo@nospan.on.net>

As already stated, I can usually whack out a concise, tight solution in Perl in just a little bit of time. I'm anxious to see if I can get to that place in Ruby and what that would look like. This sounds like Ruby might be more suited to "bigger" tasks and Perl to the small ones. I'm sure others will jump in here momentarily and dispute this...

One of the things that thrilled me with ruby was that
it didn't force me to give up quick one-off hack style
scripting, in order to have a cleaner language for bigger
tasks....

I invoke ruby from the command line fairly frequently,
for random things like:

ruby -i -pe 'gsub(/\015/,"")' *.cpp *.h

If I recall my perl correctly (been about three years now)
the perl is slightly shorter:

perl -i -pe 's/\015//g' *.cpp *.h

But ruby has proved sufficiently concise for my needs in this regard. Actually, sometimes the ruby comes out
shorter than what I think the equivalent perl would be.

Couple days ago a friend who has been learning ruby
asked me about making a program to gather and print a
sorted list of all unique IP addresses in a logfile he
had. (He said a simple string-based sort was OK, and
the logfile structure was simple enough that a very
basic regexp would identify IP addrs without false
positives.) I first approached the problem with a
hash, as I would have in Perl... and then I remembered
ruby has Array#uniq.... So the solution ended up
being:

puts ARGF.read.scan(/\d+\.\d+\.\d+\.\d+/).uniq.sort

This is where I'm looking to get with Ruby and I still reach for Perl because I don't know Ruby as well. It happened today at work. I needed to extract some server names from a piece of Perl code (text) that looked like this:

  { SERVER => "servername1", SHARE = $Default },
  { SERVER => "servername2", SHARE = $Default },
  { SERVER => "servername3", SHARE = $Default },
  { SERVER => "servername4", SHARE = $Default },
  { SERVER => "servername5", SHARE = $Default },
  { SERVER => "servername6", SHARE = $Default },
  { SERVER => "servername7", SHARE = $Default },
  { SERVER => "servername8", SHARE = $Default },

(The server names were more unique than the contrived names above.) In Perl it was:

perl -e 'while (<>) { /"(\w*)"/; print "$1\n" }' file-snippet.txt

In Ruby? I didn't have the time to figure it out. Which is the agonizing point. Later, I did the following in Ruby to satisfactory effect:

ruby -e 'ARGF.each { |line| line.scan( /"(\w*)"/ ) { |frag| puts frag } }' file-snippet.txt

Perhaps someone can refine this while we're at it. It's hard not to notice that the Perl was more concise. Perhaps my ignorance can be made right...? Can this be shortened in Ruby? Surely...

-ceo

Phil Tomson wrote:

In article <20040915185304.GD4046@lb.tenfour>,

* Phil Tomson <ptkwt@aracnet.com> [0909 19:09]:

.... You know all of the methods that will operate on a particular object of a certain class (or you can easily find out) and there were more methods available on builtin classes (for example, look at all of the methods available on Array objects and compare with functions available in Perl to operate on @list objects).

That's something that shouldn't be overlooked -

when I went back to perldoc after maybe 9 months away from Perl I had
major problebs remembering the right function to do a particular bit
of manipulation on a Hash. perldoc -f isn't much use without a method name,
and even Google is only useful if can say what you want :slight_smile:

With Ruby it was just 'ri Hash;ri Enumerable' to see all the methods
that worked on a Hash.

Or in irb: > Array.methods.sort
=> ["&", "*", "+", "-", "<<", "<=>", "==", "===", "=~", "", "=", "__id__", "__send__", "all?", "any?", "assoc", "at", "class", "clear", "clone", "collect", "collect!", "compact", "compact!", "concat", "delete", "delete_at", "delete_if", "detect", "display", "dup", "each", "each_index", "each_with_index", "empty?", "entries", "eql?", "equal?", "extend", "fetch", "fill", "find", "find_all", "first", "flatten", "flatten!", "freeze", "frozen?", "grep", "hash", "id", "include?", "index", "indexes", "indices", "inject", "insert", "inspect", "instance_eval", "instance_of?", "instance_variable_get", "instance_variable_set", "instance_variables", "is_a?", "join", "kind_of?", "last", "length", "map", "map!", "max", "member?", "method", "methods", "min", "nil?", "nitems", "object_id", "pack", "partition", "pop", "private_methods", "protected_methods", "public_methods", "push", "rassoc", "reject", "reject!", "replace", "respond_to?", "reverse", "reverse!", "reverse_each", "rindex", "select", "send", "shift", "singleton_methods", "size", "slice", "slice!", "sort", "sort!", "sort_by", "taint", "tainted?", "to_a", "to_ary", "to_s", "transpose", "type", "uniq", "uniq!", "unshift", "untaint", "values_at", "zip", "|"]

More "Wow!" You can't do this in Perl (unless you call in another CPAN module to pick apart another module. Hardly compariable.)

I becoming quite glad I've started this discussion. I'm thinking I'm just about taken in with this. Beautiful.

-ceo

···

Dick Davies <rasputnik@hellooperator.net> wrote:

Gavin Sinclair wrote:

···

On Thursday, September 16, 2004, 4:29:50 AM, Chris wrote:

Bill Guindon wrote:

On Wed, 15 Sep 2004 23:54:51 +0900, Chris <ceo@nospan.on.net> wrote:

I perceive, from what I've read, that this could be the case. I see all
these "testimonials" that claim rapid development and this is inticing,
yet at the same time, having done *some* Ruby coding, this is a little
hard for me to believe because in my estimation, the paradigm in Ruby is
entirely different than in just about any other procedural language and
even from the OO aspects of Perl, C++ and Java. To me, the difference
between Ruby and just about anything else (common) is the same as when,
in the development world, many of us made the leap from procedural to
OO. I think the gap between Ruby and most everything else is that big
-- as well as the payoffs...?

One of the payoffs is the opportunity to think differently :slight_smile:

Absolutely. One of my primary intriques with Ruby, to be sure...

In that case, I suggest you simply read Pickaxe II for pleasure. It's
a good survey of how to accomplish things in Ruby, and the available
libraries to help you.

By the time you finish, you'll have enjoyed thinking differently and
picked up enough Ruby idioms to know what's going on.

I'll look for it. This thread has been a load of fun and more than helped me get the perspective I was looking for.

-ceo

You're really better off using interpolation there:

@total = 12345
puts "Total: #{@total}"

Now, you don't have to know whether @total is a Fixnum, String, Float,
or even a hypothetical Money class.

-austin

···

On Thu, 16 Sep 2004 22:26:24 +0900, James Edward Gray II <james@grayproductions.net> wrote:

On Sep 16, 2004, at 2:44 AM, Robert Klemme wrote:
> Under which circumstances do you need to_s for numbers? What's wrong
> with this?
It's usually when I'm doing something like:

puts "Total: " + 12345

--
Austin Ziegler * halostatue@gmail.com
               * Alternate: austin@halostatue.ca
: as of this email, I have [ 6 ] Gmail invitations

"Nate Smith" <nsmith5@nist.gov> schrieb im Newsbeitrag
news:1095340527.2816.33.camel@circuit.eeel.nist.gov...

> Under which circumstances do you need to_s for numbers? What's wrong

with

> this?
>
> >> puts 1
> 1
> => nil
> >> print 1, "\n"
> 1
> => nil
> >> puts "foo #{1} bar"
> foo 1 bar
> => nil

Try

print "a" + 1

Won't work -- you have to do

print "a" + 1.to_s

I prefer to use #{} in those cases (see above, no. 3). Gives you more
control.

Of course, your example can be written much easier:

print "a", 1

Kind regards

    robert

That "+" means you're building a new string from two Strings. Since the
second operand is not a String, the conversion has to be explicit.

Now, for simple printing, it just occurred to me to test what happens
when you hand a printf-style expression to print, as I might do in the
same situation with Python:

irb > print "a%d" % 1
a1 => nil

So, that's One Way To Do It.

-- Brian Wisti
http://coolnamehere.com/

···

--- Nate Smith <nsmith5@nist.gov> wrote:

Try

print "a" + 1

Won't work -- you have to do

print "a" + 1.to_s

Nate

"Karl von Laudermann" <doodpants@mailinator.com> schrieb im Newsbeitrag
news:729e3289.0409160820.19e4ca9@posting.google.com...

"Robert Klemme" <bob.news@gmx.net> wrote in message

news:<2qsugrF13g5akU1@uni-berlin.de>...

> "James Edward Gray II" <james@grayproductions.net> schrieb im

Newsbeitrag

> news:CBB35FB8-0732-11D9-B224-000A95BA45F8@grayproductions.net...
>
> > I feel Perl has a slight edge in quick and dirty scripting. Simple
> > things like having to call to_s() on the integers I print or
>
> Under which circumstances do you need to_s for numbers?

I can't speak for James, but coming from Java I'm used to using the
concatenation operator, like so:

print "foo" + 1;

This causes an error; you have to call to_s on the number. I find it
unintuitive that specifying multible arguments to the print method is
a way of concatenating them, so I rarely think to use it.

Others might think different about this - I do for example. :slight_smile: You
simply enumarate things to get printed. Also, it's more efficient to
individually print items than to first concatenate them (creates new temp
instances) and then print that temp String instance. If I have more
complex printouts I use String interpolation with "#{}" or printf anyway.

I also find
it unintuitive that you don't have to call to_s when passing a
non-string argument by itself, but you do when concatenating.

It's perfectly logical because these are two completely unlelated things:
String#+ is something different than the behavior of Kernel#print.

Perhaps
String#+ should be modified to call to_s on its arguments?

It is done deliberately the way it is: String#+ is "intelligent" enough to
invoke #to_str on its arguments; but an instance that has no #to_str
cannot be "legally" concatenated with a String.

class Foo; def to_str; "xxx" end end

=> nil

Foo.new

=> #<Foo:0x10187990>

Foo.new.to_str

=> "xxx"

puts "2" + Foo.new

2xxx
=> nil

BTW, one actual benefit of using concatenation vs. multiple arguments
is that you can use puts instead of print to get a "\n" for free at
the end, but not in between each component of your string.

Well, you can use puts with interpolation or define a println method if
you really care to save the "\n" typing effort:

module Kernel
private
  def println(*args) print *args << "\n" end

  def smart_println(*args)
    args << "\n" unless /\n$/ =~ args[-1].to_s
    print *args
  end
end

Kind regards

    robert

Man, why can't you guys be up here in Seattle? It's just a few miles
away. I'm sure Intel can move every building, person, and project up
here.

You know we're the cool kids, right? :wink:

-- Brian Wisti

···

--- Lennon Day-Reynolds <rcoder@gmail.com> wrote:

On Thu, 16 Sep 2004 03:46:00 +0900, Curt Hibbs <curt@hibbs.com> > wrote:
> [...]
> Very interesting... I don't know where your "area" is, where is all
this
> happening?
>
> Curt
>

Portland, OR, and the surrounding 'burbs. I'm working at Intel using
Ruby right now, (in a position which Phil vacated a few months ago)
and we're looking to hire another coder to work with me. We're not
the
only group in-house using Ruby either; we're just (AFAIK) the first
of
be hiring Ruby coders specifically.

Brian Wisti wrote:

Or in irb: > Array.methods.sort

<snip>

This is one of those situations where I kinda miss Python and its
ability to store and later display the docstring of a function or class
when requested.

One thing at a time, I suppose.

Why bloat the ruby executable with docstrings when you can easily add ri to irb? After all, irb is where you want to access the docs. Here's the relevant part of my .irbrc:

def ri arg
   puts `ri #{arg}`
end

class Module
   def ri(meth=nil)
     if meth
       if instance_methods(false).include? meth.to_s
         puts `ri #{self}##{meth}`
       end
     else
       puts `ri #{self}`
     end
   end
end

Bill Kelly wrote:

In article <8x%1d.2604$Qv5.529@newssvr33.news.prodigy.com>,

(4) Each language has it's own strengths. IMO one of Perl's strengths is the simplicity and consistency of it's parameter passing:

sub shell {

  my @output;
  for (@_) { push @output, `$_` }
  chomp( @output );
  return wantarray ? @output : \@output;

}

In ruby that might be,

def shell(*args)
  args.map {|a| `#{a}`.chomp}
end

..It's true you'll always get an array back. But if
you want to splat the array such that you can assign
its individual element(s) to variables you can...

a = shell("echo 1", "echo 2") # a => ["1", "2"]
a,b = *shell("echo 1", "echo 2") # a => "1", b => "2"

Ew... thanks for writing that. I had not yet gotten to the point of converting my Perl shell() routine to Ruby, but this puts (ha!) me ahead a little bit. I wrote the shell() routine in Perl simply as a reverse example; I wasn't asking how to do it in Ruby. This "puts" you into the bonus round... :slight_smile:

-ceo

···

Chris <ceo@nospan.on.net> wrote:

Hello ChrisO,

I agree with Phil that the unspecified parameters is one of the worst
things in Perl.

But aside from the undisciplined uses you've pointed out as reason for
eshewing this in Perl, I have to wholy stand by the amazing power this
feature brings. It far outweighs the negatives. It's one of the
"genius" things about Perl. (Always educational, however, to get
someone else's opposite point of view, as you have offered.)

I don't care if you are disciplined enough and can do nice hacks with
this "genius" things. Software is written and maintained by a lot of
different people. If you have to read other persons source code you
are normally lost. I have once seen the argument that a brush
shouldn't restrict the work of painter, and so a language shouldn't
restrict the work of a "genius" programmer but i don't agree with this.

Enforcing styles is good and more productive in the long run.

And to bring this Perl discussion back on topic, in line with your
dislike of this "feature" in Perl, am I not correct in understanding
that in Ruby, one can create methods on the fly in a class? How is this
that much different (conceptually) than unspecified parameters in a Perl
subroutine? How do you know what methods are there (aside from using
the inspection methods available to every class [unless I am mistaken in
this regard]).

The difference is that the Ruby method is only used in very very
special cases and should not be seen a good style of programming
without good reasons. I think the TK bindings source code is a good example to
not use this feature. But the perl solution is something that you
must use all the time. So you can't compare the two cases.

···

--
Best regards, emailto: scholz at scriptolutions dot com
Lothar Scholz http://www.ruby-ide.com
CTO Scriptolutions Ruby, PHP, Python IDE 's

ChrisO wrote:

This is where I'm looking to get with Ruby and I still reach for Perl because I don't know Ruby as well. It happened today at work. I needed to extract some server names from a piece of Perl code (text) that looked like this:

    { SERVER => "servername1", SHARE = $Default },
    { SERVER => "servername2", SHARE = $Default },
    { SERVER => "servername3", SHARE = $Default },
    { SERVER => "servername4", SHARE = $Default },
    { SERVER => "servername5", SHARE = $Default },
    { SERVER => "servername6", SHARE = $Default },
    { SERVER => "servername7", SHARE = $Default },
    { SERVER => "servername8", SHARE = $Default },

(The server names were more unique than the contrived names above.) In Perl it was:

perl -e 'while (<>) { /"(\w*)"/; print "$1\n" }' file-snippet.txt

In Ruby? I didn't have the time to figure it out. Which is the agonizing point. Later, I did the following in Ruby to satisfactory effect:

ruby -e 'ARGF.each { |line| line.scan( /"(\w*)"/ ) { |frag| puts frag } }' file-snippet.txt

Perhaps someone can refine this while we're at it. It's hard not to notice that the Perl was more concise. Perhaps my ignorance can be made right...? Can this be shortened in Ruby? Surely...

Golf.shoes = "on"

$ ruby -n -e 'puts $1 if /"(\w+)"/' file-snippet.txt
servername1
servername2
servername3
servername4
servername5
servername6
servername7
servername8

ruby -e 'puts ARGF.grep(/"(\w*)"/) {$1}' file-snippet.txt

I'd bet it could be shorter still, but It's all new to me too :slight_smile:

···

On Thu, 16 Sep 2004 09:14:51 +0900, ChrisO <ceo@nospam.on.net> wrote:

This is where I'm looking to get with Ruby and I still reach for Perl
because I don't know Ruby as well. It happened today at work. I needed
to extract some server names from a piece of Perl code (text) that
looked like this:

        { SERVER => "servername1", SHARE = $Default },
        { SERVER => "servername2", SHARE = $Default },
        { SERVER => "servername3", SHARE = $Default },
        { SERVER => "servername4", SHARE = $Default },
        { SERVER => "servername5", SHARE = $Default },
        { SERVER => "servername6", SHARE = $Default },
        { SERVER => "servername7", SHARE = $Default },
        { SERVER => "servername8", SHARE = $Default },

(The server names were more unique than the contrived names above.) In
Perl it was:

perl -e 'while (<>) { /"(\w*)"/; print "$1\n" }' file-snippet.txt

In Ruby? I didn't have the time to figure it out. Which is the
agonizing point. Later, I did the following in Ruby to satisfactory effect:

ruby -e 'ARGF.each { |line| line.scan( /"(\w*)"/ ) { |frag| puts frag }
}' file-snippet.txt

Perhaps someone can refine this while we're at it. It's hard not to
notice that the Perl was more concise. Perhaps my ignorance can be made
right...? Can this be shortened in Ruby? Surely...

--
Bill Guindon (aka aGorilla)

In article <ER32d.2786$Qv5.1325@newssvr33.news.prodigy.com>,

Phil Tomson wrote:

In article <8x%1d.2604$Qv5.529@newssvr33.news.prodigy.com>,

(4) Each language has it's own strengths. IMO one of Perl's strengths
is the simplicity and consistency of it's parameter passing:

sub shell {

  my @output;
  for (@_) { push @output, `$_` }
  chomp( @output );
  return wantarray ? @output : \@output;

}

Actually, I think this is one of the _worst_ things about Perl and it was
one of those nagging little annoyances that when added up finally led me
to seek out alternatives. The problem with the way parameters are passed
to subroutines in Perl is that you can't tell from a glance how many
params are supposed to be passed into the subroutine and you have no
information about what the params are. You've got to look down through
the subroutine code to see if there's a 'shift @_' lurking somewhere in
the code (for the uninitiated, you pass params to Perl subroutines via the
'@_' global list; you have to 'manually' shift the params off of that list
- blech! )

An incredibly interesting point of view though your justification for it
is somewhat understandable. Pathological mistakes can occur this way
for those that use this, what I would call an incredibly nice feature,
in an undisciplined way. I'm quite disciplined about spiking out my
arguments in Perl at the top of a subroutine.

Did you do this in comments? In my faint recollections of Perl I seem to
recall that there was a way to declare the sub with it's params - but most
people didn't do this (or perhaps my memory is incorrect).

I think your dislike
perhaps has been fueled by people that write subroutines in a "hackish"
sort of way. (I would imagine "hacking" Ruby is just as possible to
accomplish.)

But aside from the undisciplined uses you've pointed out as reason for
eshewing this in Perl, I have to wholy stand by the amazing power this
feature brings. It far outweighs the negatives. It's one of the
"genius" things about Perl. (Always educational, however, to get
someone else's opposite point of view, as you have offered.)

Essentially what you're trying to get is to be able to pass in a variable
number of arguments to a method (err, function in Perlese). Ruby lets
you do that like so:

  def foo(*args)

At least in this case you can tell at a glance that foo can take a
variable number of arguments.

In perl you could have:
  
  sub foo {
    
    for(@_) {... do whatever...}

  }

In the case of Perl, I've got to actually go and read the body of the
function to know that it can take multiple arguments. I don't like it.

The other thing I don't like about it is that it means that argument
handling in Perl is a do-it-yourself project (like OO Perl)

And to bring this Perl discussion back on topic, in line with your
dislike of this "feature" in Perl, am I not correct in understanding
that in Ruby, one can create methods on the fly in a class? How is this
that much different (conceptually) than unspecified parameters in a Perl
subroutine?

It could present similar problems, however, creating methods on the fly,
while possible, it's relatively unusual compared to what we're talking
about in Perl. Every sub in Perl requires that I read the body of the sub
to determine what the args are and how many. I would also contend that
the 'problem' of creating methods on the fly is not as big because what is
happening is that you're getting some new feature (a new method) created
on the fly (or perhaps you're overriding an old one) that you may not be
aware of - not knowing about a new method won't break anything because
you probably won't call what you don't know about. :wink:

How do you know what methods are there (aside from using
the inspection methods available to every class [unless I am mistaken in
this regard]).

I'll give you a better example for your the point you're trying to make: yield.

In Ruby you can have:

  def foo
    #...
      yield
    #...
  end

Now there is no indication from looking at the method definition line (the
'def foo' part) that any argument is passed to this method, yet it
requires that a block be passed to it, like so:

  foo { puts "Boo!" }

So, it's a bit like the problem I'm talking about with Perl, except that
in practice it's not as bad because usually there is only one yield in a
method - but it can be an issue. That's why it's probably better to do:

  def foo(&b)
    #...
    b.call
    #...
  end

Because it provides the reader of the code with a clear indication that
the method takes a block. Also, it's usually a good idea if you do use
yield to also call 'block_given?' prior to yielding.

Phil

···

ChrisO <ceo@nospam.on.net> wrote:

Chris <ceo@nospan.on.net> wrote:

Phil Tomson wrote:

>In article <20040915185304.GD4046@lb.tenfour>,
>
>>* Phil Tomson <ptkwt@aracnet.com> [0909 19:09]:
>>
>>
>>>.... You know all of the methods that will operate on a particular
>>>object of a certain class (or you can easily find out) and there were
>>>more methods available on builtin classes (for example, look at all of
>>>the methods available on Array objects and compare with functions
>>>available in Perl to operate on @list objects).
>>
>>That's something that shouldn't be overlooked -
>>
>>when I went back to perldoc after maybe 9 months away from Perl I had
>>major problebs remembering the right function to do a particular bit
>>of manipulation on a Hash. perldoc -f isn't much use without a method
>>name,
>>and even Google is only useful if can say what you want :slight_smile:
>>
>>With Ruby it was just 'ri Hash;ri Enumerable' to see all the methods
>>that worked on a Hash.
>>
>
>
>Or in irb:
> > Array.methods.sort
>=> ["&", "*", "+", "-", "<<", "<=>", "==", "===", "=~", "", "=",
>"__id__", "__send__", "all?", "any?", "assoc", "at", "class", "clear",
>"clone", "collect", "collect!", "compact", "compact!", "concat", "delete",
>"delete_at", "delete_if", "detect", "display", "dup", "each",
>"each_index", "each_with_index", "empty?", "entries", "eql?", "equal?",
>"extend", "fetch", "fill", "find", "find_all", "first", "flatten",
>"flatten!", "freeze", "frozen?", "grep", "hash", "id", "include?",
>"index", "indexes", "indices", "inject", "insert", "inspect",
>"instance_eval", "instance_of?", "instance_variable_get",
>"instance_variable_set", "instance_variables", "is_a?", "join",
>"kind_of?", "last", "length", "map", "map!", "max", "member?", "method",
>"methods", "min", "nil?", "nitems", "object_id", "pack", "partition",
>"pop", "private_methods", "protected_methods", "public_methods", "push",
>"rassoc", "reject", "reject!", "replace", "respond_to?", "reverse",
>"reverse!", "reverse_each", "rindex", "select", "send", "shift",
>"singleton_methods", "size", "slice", "slice!", "sort", "sort!",
>"sort_by", "taint", "tainted?", "to_a", "to_ary", "to_s", "transpose",
>"type", "uniq", "uniq!", "unshift", "untaint", "values_at", "zip", "|"]
>

More "Wow!" You can't do this in Perl (unless you call in another CPAN
module to pick apart another module. Hardly compariable.)

I becoming quite glad I've started this discussion. I'm thinking I'm
just about taken in with this. Beautiful.

also if your .irbrc includes "require 'irb/completion'" you can tab
complete methods:

    e.g.
    >> "The Boat Arrived!".s<Tab><Tab>
    .scan .sort .sub
    .select .sort_by .sub!
    .send .split .succ
    .singleton_methods .squeeze .succ!
    .size .squeeze! .sum
    .slice .strip .swapcase
    .slice! .strip! .swapcase!
    >> "The Boat Arrived!".sum - 1
    => 1492

marcel

···

On Thu, Sep 16, 2004 at 09:24:49AM +0900, ChrisO wrote:

>Dick Davies <rasputnik@hellooperator.net> wrote:

--
Marcel Molina Jr. <marcel@vernix.org>

An excellent point. Thanks for the tip.

James Edward Gray II

P.S. As I said in the original post, most of my issues probably come

···

On Sep 16, 2004, at 8:32 AM, Austin Ziegler wrote:

You're really better off using interpolation there:

@total = 12345
puts "Total: #{@total}"

Now, you don't have to know whether @total is a Fixnum, String, Float,
or even a hypothetical Money class.

from my lack of familiarity.