Slashdot Mirror


User: baldur

baldur's activity in the archive.

Stories
0
Comments
1
First seen
Last seen
Profile
(view on slashdot.org)

Comments · 1

  1. Ruby vs. Perl code shoot-out on Ruby-Is it Prettier than Perl? · · Score: 3

    I'm just starting to try Ruby out, and I haven't used it for anything big or important yet, but it seems to me that its main advantage is being rather more readable and probably more maintainable than Perl (which I still haven't stopped loving anyway...). Here is a small sample, lifted directly from the cgi.rb module:


    def CGI::parse(query)
    params = Hash.new([])
    query.split(/[&;]/n).each do |pairs|
    key, value = pairs.split('=',2).filter{|v| CGI::unescape(v) }
    if params.has_key?(key)
    params[key].push(value)
    else
    params[key] = [value]
    end
    end
    params
    end

    Now, a more or less "literal" translation into Perl would look like this:


    sub CGI::parse {
    my $query = shift;
    my %params;
    foreach $pair (split(/[&;]/, $query)) {
    my ($key,$value) = map { CGI::unescape(\$_) } split(/=/,$pair,2);
    if (defined($params{$key}) {
    push @{$params{$key}}, $value;
    else {
    $params{$key} = [$value];
    }
    }
    %params;
    }

    Despite superficial differences, you are able to tell from this example that the strongest influence on Ruby has been Perl. The examples are essentially the same. Someone with a background in Perl (like myself) has a much easier time learning Ruby than, for instance, Python.

    What I like about Ruby:

    • Less punctuation than Perl and hence more readable. (This applies to braces, parentheses and semicolons, and maybe also the Perl vartype-symbols $, @ and % - though I'm of two minds about those, as I also think they contribute to clarity in most cases).
    • You don't have to use local or my to get local/lexical variables. Variables in Ruby are local (not lexical) by default. (When I'm writing Perl, about 95% of the variables I use are lexical. That's a lot of my's!)
    • The way you can easily string methods after each other using dot notation: variable.method1.method2(/regex).method3
    • The way you can easily act on a reference rather than return a value, using "!", as in str.gsub!(/\"/n, '"'). (Although this particular example would be a bit more compact in Perl: $str=~s/\"/"/g).

    What I don't like about Ruby:

    • The iterator syntax (array.iterate{|v|, do_something(v)}), which admittedly is quite logical but for some reason gets on my nerves.
    • No use strict.
    • No CPAN (though The Ruby Application Archive is a good start).
    • No poetry... at least not yet.

    So, on the whole I think Ruby is quite nice. I'll follow its further development with great interest. But for now, I'm too attached to Perl to make the switch.