
Comparing PHP, Perl, Python and Ruby - charlax
http://hyperpolyglot.org/scripting
======
raymondh
This is a wonderful recap of the different ways of expressing the same idea in
different languages. It is a fine Rosetta Stone.

That being said, it would also be useful to characterize features that are
completely unique to a given language. For example, Python has 1) a unique and
powerful version of super() for working with multiple inheritance; 2) it has
generators (the yield statement) that allows state to be suspended and
restarted (and allows data and/or exceptions to be passed back in to the
generator); 3) the with-statement for managing contexts and for providing a
new way to factor code; 4) easy-to-write class and function decorators; 5)
metaclass support that provides full control over the creation of classes; 6)
and descriptors for fine-control over attribute/method binding behavior.

Collectively, these capabilities make the language more than just another
syntax for expressing the same ideas as other languages.

~~~
jrockway
_That being said, it would also be useful to characterize features that are
completely unique to a given language._

Perl has all these features.

 _1) a unique and powerful version of super() for working with multiple
inheritance_

Perl (with Moose) has before, after, around, override, and augment in addition
to super. And, it has "Roles" so you don't have to resort to hacks like
multiple inheritance to implement mixins or interfaces.

 _2) it has generators (the yield statement) that allows state to be suspended
and restarted (and allows data and/or exceptions to be passed back in to the
generator)_

Perl has the library Coro, which allows multiple Perl and C stacks. With this
coroutine and call-with-current-continuation are implemented.

 _3) the with-statement for managing contexts and for providing a new way to
factor code_

Perl has scope a few implementations of scope guards; Guard and Scope::Guard.
It's not quite the same as with, because with's semantics around:

    
    
       with open_file('foo') as f:
           return f
    

are unclear (f is closed but the object still exists). Perl mixes

    
    
       sub x {
          my $f = file('foo')->openr;
          return $f; # $f is still open and ready for reading by the caller
       }
    

Emulating Python is still possible, however:

    
    
       sub x {
           my $f = file('foo')->openr;
           scope_guard { $f->close }
           return $f; # caller gets a closed file object
       }
    

_4) easy-to-write class and function decorators_

This you don't really get, though you do get all of the things I've seen them
used for in Python. You can even hack Perl syntax in a lexical scope, but
that's evil so I will pretend it's impossible :)

 _5) metaclass support that provides full control over the creation of
classes; 6) and descriptors for fine-control over attribute/method binding
behavior_

Moose. And unlike Python, there are libraries that take advantage of this to
provide tiny bits of OO functionality that you can pick and choose from. Look
on CPAN for a MooseX:: module, and chances are that the set of libraries you
choose to use to augment a class will all work together.

The difference between Perl and Python is that Perl's features are implemented
as modules, while Python's features are implemented in the core. That means
that if you come up with a good idea, you can start using (and sharing) it
immediately, while with Python, you have to wait until the next major release.

~~~
neilk
It also means you have to stumble upon Moose to start using objects in a
reasonably sane way. The average new Perl programmer is not going to go
looking for a library that does object-oriented behavior until it's too late.
They'll probably have some crazy idea that the language should be doing OO for
them.

If you were to navigate a largish Perl codebase today, you'd encounter the
old-school bless, Moose trickiness, and all kinds of variants on these themes.
Extremely clever stuff that Damian Conway would give you a gold star for.

As usual Perl gives you everything you want, unless what you wanted was
simplicity or standardization.

~~~
berntb
>>The average new Perl programmer is not going to go looking for a library
that does object-oriented behavior until it's too late.

Sigh, _please_ don't start language wars by stuff like assuming new
programmers sits alone in an ivory tower and don't talk to people, read blogs
or browse a new book. (Modern Perl discuss Moose before the old standard, for
instance.)

Edit: I'm just not going to touch where you assume all Perl teams that write
large code bases are too stupid to agree on best practices. (I'll ask this
back instead: Why are there so many language wars-lovers in some open source
communities...?)

~~~
jrockway
_Why are there so many language wars-lovers in some open source
communities...?_

Probably the same reason the French don't like the English or the Indians
don't like the Pakistanis. The closer two things are to each other, the more
passionate people are about the differences.

My experience is that all the languages are identical. Python has a culture of
cleanliness at the core, but there is a lot missing from the language that
makes it unclean in practices. (See: the investment bank I worked where all
new apps were written in a C#/C++/Python trialect, to coin a new word.) Perl
is a very messy language, but the community has hyper-overreacted and have
made a very clean set of "best practices". I haven't done much Ruby, but I
can't say anything other than that it looks like a combination of Perl and
Python, with a relatively new community around it.

These three languages are largely the same thing: they run slow and they're
fun to write. Hence all the infighting.

~~~
_sh
Learning a language is an investment. People defend their investment
strategies lest they be considered a fool. Attacking alternatives is a form of
defense. I fear it's as simple as that.

~~~
berntb
The original question was -- why do _some_ communities seem to be more
oriented towards language wars than others?

~~~
zoul
Can't speak for all of them, but if a language has "there's more than one way
to do it" as its main motto, I guess the people from the ecosystem are less
likely to attack other languages.

------
rll
Note that anywhere you see array() in that list for PHP 5.4 you can replace it
with [ ]'s. So the example that has:

    
    
      $a = array(1,2,array(3,4));
    

becomes:

    
    
      $a = [1,2,[3,4]];
    

Also

    
    
      0b101010
    

works in 5.4.

~~~
Klinky
True, but PHP 5.4 doesn't even have a stable release yet & many people haven't
even adopted 5.3.

~~~
robryan
5.3 Come out in 2009, I has a small list of backwards compatibility breaking
changes (<http://www.php.net/manual/en/migration53.incompatible.php>), no
reason for anyone really not to have adopted it.

~~~
mmj48
> many people haven't even adopted 5.3.

> no reason for anyone really not to have adopted it.

These things are not mutually exclusive. I.e. you could be write, but Klinky
definitely is.

~~~
robryan
True, I think it is a valid point for arguments about language features
though. Fair enough to say that anything in 5.4 isn't production ready yet or
had the time to trickle down to hosts but you can't judge PHP on versions
before 5.3 as anyone can put a small amount of effort in and have everything
5.3 has to offer.

------
verelo
This is great. Very handy for explaining to others the differences between
various languages, and surprisingly enough until you get into the array
functions i'm starting to feel like PHP isn't really that messy since reading
this!

Thanks for sharing, ill pass it on whenever a comparison is needed.

~~~
leftnode
PHP5.4 also has the short syntax array initializer:

    
    
        $array = [1, 2, 3];
    

Edit: While PHP still has it's fair share of issues, a lot of the same
complaints people had 5-8 years ago aren't valid, and it probably has no more
or less oddities than any other scripting language at this point.

~~~
jacques_chester
The problem with PHP is that 99.99% of the code in circulation today isn't the
shinier cleaned-up versions. It's PHP4 and PHP 5.0 and it's still chock-a-
block with the storied mind-bending nastiness of yore.

~~~
gregbair
not true at all. Maybe if you're looking at old sites, but PHP5's been out for
a long time now, and most of the code in circulation is made for 5.2 or
higher. No serious MVC framework, for instance, will run on anything less than
5.2.

~~~
jacques_chester
Serious MVC frameworks are not the backbone of Wordpress, phpBB or dozens of
other hairy monsters that make up the majority of CPU time spent on PHP
execution.

I mean Wordpress flat out resisted PHP 5.0 for years. _Years_. Everything had
to be done in PHP4.

~~~
jmathai
> I mean Wordpress flat out resisted PHP 5.0 for years. Years. Everything had
> to be done in PHP4.

I presume that's because of the size of Wordpress' install base. The number of
people who run their software on $9/month shared hosting environments is
staggering. Many of those are late to upgrade PHP versions.

Wordpress gets a lot of crap for being poorly written but the truth is that
it's an example of software that works really well given some really unique
circumstances. If the WP devs decided that their software didn't need to
support the 99% of web servers out there then it wouldn't be nearly as
ubiquitous as it is today.

~~~
jacques_chester
Wordpress gets a lot of crap for being poorly written because it is _poorly
written_. There's no great mystery here.

Yes, they deal with lots of different configurations. This is _not_ unique in
the history of software development. It's called "portability" and many
organisations seem to be able to achieve it without compromising quality.

My searing, eye-boiling hatred for Wordpress comes from administering it for
what is now nearly a decade. Every time I dive into the code I am frequently
repulsed by it.

The total absence of tests is my favourite "feature". I've seen multiple bugs
closed with WORKSFORME that I was directly grappling with.

~~~
robryan
You are right it is far from perfect, it is pragmatic and providing a great
amount of value for people/ businesses. It is surprising to me that we haven't
seen a big challenger trying to do it right from a back end perspective.

~~~
jacques_chester
Because users don't care about the backend. They care about the shiny
features, look-and-feel and the availability of plugins and themes.

Wordpress delivers these in spades.

------
notJim
This is a really great effort, but I noticed a handful of areas where the PHP
example was off. I wonder if people with more experience with the other
languages noticed the same thing for their language.

Some examples:

Null test:

    
    
        $var === null // omitted
        isset($var) // actually checks if $var exists and is not null (apparently--
            I actually didn't know about the not null part)
    

Undefined variable access: it's a notice. Many people consider it best
practice in PHP to treat notices as error, because things like this are
notices.

Add time duration

    
    
        strtotime('+10 minutes') is more typical than the objects
    

Array out of bounds behavior again issues a notice.

~~~
MattBearman
I noticed that block statements were missing from PHP, eg: using if(): ...
endif; etc. instead of if(){ ... }

------
ars
Previous discussion: <http://news.ycombinator.com/item?id=2882070> with lots
of bug reports. I wonder if they incorporated all the changes suggested.

------
jablan
"Passing by reference" section is wrong about Ruby (not sure about Python).
Ruby passes everything by reference, it's only that integers are immutable so
that the function can't alter them. Strings, though, are mutable:

    
    
      def foo s
        s.concat 'foo'
      end
      a = 'bar'
      foo a
      a
      # => "barfoo"

~~~
vidarh
Well, integers are immutable (and conceptually a singleton per value) _unless
you override stuff in FixNum and add instance variables_. Here's an evil
example that works at least in MRI 1.8.6:

    
    
        class Fixnum
    
          alias :realplus :+
        
          def + b
            @a ||= 0
            @a = @a.realplus(b)
            self.realplus(@a)
          end
        end
    

The integer value itself is immutable, though.

Of course all hell will break loose _and_ adding instance variables in certain
classes like Fixnum will be extra slow (as if there aren't enough other
reasons not to), since MRI uses type-tagging for Fixnum, Symbol and a few
others, and so since they're not "real" objects, if you do anything that
requires one, it creates one that's stored in a hash table.

------
tikhonj
Here's a simpler comparison with _way_ more langauges:
[http://rigaux.org/language-study/syntax-across-
languages/Str...](http://rigaux.org/language-study/syntax-across-
languages/Strng.html#8)

------
citizenkeys
sed begat awk.

awk begat perl.

perl begat python and ruby.

python will get you a job at google.

ruby will get you a job at twitter.

php will get you a job at facebook.

~~~
wildtype
_ruby will get you a job at twitter._

I heard that twitter are moving from ruby to scala.

~~~
desireco42
that was more then a year or two ago, they changed their mind in the meantime.
they do have some cool software developed in scala I think.

~~~
densh
Do you have any support for this statement? Last time I checked they moved all
of the api and backend infrastructure to Scala and were quite happy with it.

------
smsm42
Unfortunately tests page for PHP does not mention PHPUnit:
<http://www.phpunit.de/manual/3.6/en/index.html> which is the best solution
for testing in PHP. Neither it mentions xdebug for debugging and xhprof for
profiling.

------
laichzeit0
Perl's treatment of regex still trumps all. It's so pleasant to use in so many
ways. It's for this reason alone I will probably never bother "switching" to
Python or Ruby.

~~~
crusso
Since Ruby copies Perl's regex shortcuts (blah =~ /matchme/), what's the
problem?

------
alberth
Wish Lua was added to the list.

Edit: Found Lua compared on the same site here:
<http://hyperpolyglot.org/embeddable>

------
kirinan
Very good comparison between all the languages, and like other people said: a
nice Rosetta stone. With that said, it would be very useful to add a
comparison of the database layer syntax as that it is, at least for a me, a
common task in all of the scripting languages. I also agree with the comments
about adding the features that are unique to the languages, as that would be
extremely helpful.

~~~
pavelkaroukin
there are quite a few options for syntax already in the mix, that people
noticed already. If we will add DB-related stuff, it will confuse even more -
too many options available in each language.

~~~
kirinan
Great point! Thanks for the response, and it makes sense.

------
methoddk
Bookmarked and forever using this to explain the differences between these.
Thanks for the awesome resource!

------
devy
Even though there is no native "switch" statement in Python, the same control
flow structure can be done with a dict construct:

<http://simonwillison.net/2004/may/7/switch/>

~~~
hack_edu
Whenever the debate comes up in official channels, there is near-unanimous
support for omitting it.

------
powersurge360
PHP repl is actually php -a

~~~
mikey_p
Note that this is not a traditional repl in the style of of Python or IRB that
evaluates each line individually. With php -a you have to enter an entire
script, and then exit to run it, and which point you can no longer interact
with the variables, etc. Also it's super backwards in that you need to add
<?php tags to turn interpretation on.

If you really want a repl that's useful for PHP check out
<http://www.phpsh.org/> by Facebook.

~~~
powersurge360
No, you can do evaluation line by line, but it isn't exactly nice. Just typing
php forces you to type in the entire script.

------
alexm920
Wonderful reference for comparison! I admittedly haven't had time to pursue
the whole table, but wanted to point out that there is indeed an increment and
decrement in python:

x += 1

x -= 1

~~~
mistercow
They list those under "compound assignment operators", which makes sense given
that += and -= are found in all of these languages. It's also worth noting
that compound assignment operators do not form expressions in Python. So "i++"
in PHP/Perl/Ruby is very different from "i += 1" in Python.

------
Arabian
The Perl described in this article is COMPLETE SHIT. He calls deprecated and
improper libs for some functions, unnecessary libs in others, assumes improper
or unoptimal syntax in other examples. The list goes on. Learn languages
before releasing articles on them.

He never even uses Perl's foreach in equivalency examples!! WTF.

~~~
masklinn
Not sure it's a "he", it's a wiki-type thingie.

Also, you can report bugs on the table if things are not correct.

------
joewadcan
Very helpful!! Like a quick & easy Rosetta stone

------
youlost_thegame
Very, very thorough. A great resource, thanks!

~~~
youlost_thegame

      Empty comments can be ok if they're positive. There's 
      nothing wrong with submitting a comment saying just 
      "Thanks." What we especially discourage are comments that 
      are empty and negative—comments that are mere name-calling.
    

\--<http://ycombinator.com/newswelcome.html>

------
snampall
Nice. Useful and handy.

------
berntb
A very useful page if you know one or two of those languages and need to do
something in another one.

A suggestion: For people doing some work in Perl, a review of the OO syntax
might be critical. Both Moose and the old way.

A note, re the repl part: I don't use a repl for Perl, I just write one liners
in shell. Afaik, Perl is the best command line tool that exist, it is even a
superset of awk.

Edit: For named parameters the page might want to reference one of the CPAN
modules doing that. Same goes for exceptions. The use of do to create blocks
most everywhere might also be noted in e.g. the ternary operator. Unicode
support should probably also be discussed. And so on.

------
rwmj
[I wonder if this is a personal watershed for Hacker News?]

These languages are essentially the same thing. I often write code in at least
3 of these languages most days, and I simply translate the minor differences
between them in my head.

"Hyperpolyglot" -- excess in many tongues -- I don't think so.

Learn at least some static languages, assembler and some functional languages,
and _then_ post something interesting on HN.

Well, I have plenty of karma to waste on noobs.

~~~
mattdeboard
Nothing I love more than watching someone try way too hard to act "grizzled"
and in the process make an idiot out of themselves.

<http://hyperpolyglot.org/>

~~~
whateverer
Was that in response to his exhortation to learn different languages, or do
you actually believe that Perl and its self-proclaimed successors have any
profound differences?

~~~
vidarh
I think the point is that while the article link is to the scripting category,
the site does in fact cover a lot more languages.

~~~
whateverer
Yeah, that was the first point. You can see a lot more variety of comparisons
in the main page. The categories are a bit odd at times, but it's a good stab
at being representative.

