Hacker News new | past | comments | ask | show | jobs | submit login
Comparing PHP, Perl, Python and Ruby (hyperpolyglot.org)
382 points by charlax on Feb 28, 2012 | hide | past | favorite | 87 comments



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.


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.


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.


I used to work on an old perl code base that was written by well meaning new programmers. I know work on an old python code base written by well meaning new programmers.

Both projects suck equally. The python project is much newer (~4 years instead of 12), but the smell is about the same. The problem with new programmers isn't that they pick the wrong object creation patterns, but that they reinvent the wheel and write long stupid functions with horrible nested if/else statements. A former google employee worked on one of the projects, and wrote her own python to json function.

I like python, and I like perl, but the python culture sucks. It has this weird superiority complex where it rejects any external ideas. If I am talking to perl people, and I mention some kick ass python feature that I miss, I either get information as to how it can be done in perl, or interest into why I like it. Around python people, I generally get something like, "well, none of us know perl. Have you tried doing it the python way?"

Moose is awesome, perlbrew is awesome, perl's module culture is awesome. The module culture is the one that annoys me most often. Python programmers don't write as good of tests, or nearly as good of documentation. We still have to run a lot of python 2.4, and a lot of modules claim 2.4 support and then use 2.6+ syntax.

I like python, I think it is a much better matlab, but a lot of its syntax is unintuitive and stupid, and there are some serious cultural issues. Anyone who thinks that it is perfect, or better than another language in every way is holding it back.


I agree with another comment in reply to yours that this is a tired argument.

But ignoring that; someone who is new to programming is not going to understand the value of any of these concepts anyway, so it doesn't matter that they don't discover them immediately. At about the same time people figure out how to do OO cleanly, they will start hearing about libraries too.

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.

I've worked on a number of post-Moose codebases, and most people did the conversion cleanly and all at once. (I can't explain it, I'm just reporting the facts. I was surprised too.) The biggest Moose-hacking pain point I've seen was someone trying to subclass DateTime with Moose. It just doesn't work very well; DateTime is werid and Moose is weird. (Of course, the solution is delegation rather than subclassing. Even in languages with real OO, you often want a "does X interface by delegating to Y class" rather than "isa Y".)


Fork Perl 5, package it so that Moose is default, and call it Perl 7.


If you want Python, just use Python ("There should be one-- and preferably only one --obvious way to do it." - PEP 20). Very central to the Perl philosophy is that TIMTOWTDI (though I'm not sure if this is canonized anywhere as clearly as for Python), so your suggestion is ridiculous. I for one found the bless mechanics extremely enlightening with regard to the semantics of object orientation. The feeling I had when I first got that was akin to when I first realized "to be" lumps together the semantics of identity and attribution in the english language.


I'm not a Perl programmer, but I'm aware of Moose. It's frequently mentioned in beginner tutorials on how to do OO.


You mean Moose being mentioned in Non-Perl beginner tutorials? That's interesting! Do you happen to have some links to those tutorials?


No, I mean Perl tutorials like Modern Perl.


>>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...?)


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.


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.


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


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.


>>Why are there so many language wars-lovers in some open source communities...?

Honestly, I think that the reason is simple: because it's entertaining. Yeah, sometimes I'm tired of reading the same arguments over, and over, and over again. But sometimes, an OP is particularly eloquent in his trashing a language, and I like that, even if the language he's trashing is my favorite.

The same goes with rants. I can't understand people debating over Linus Torvalds rant on C++. Honestly, I found it hilarious and well written. That's it, I'm looking no further because I know that this type of argument has no end.

I would certainly not care to debate the relative merit of my favorite language in one of those troll topics, but I do enjoy reading heated programmers exercising their writing skills against each other.


I'm pretty sure you can do the same generator does with iterators in PHP. Traits in PHP 5.4 probably cover most of use cases where you may want multiple inheritance. Decorators are superior in Python though, no real replacement for it in PHP.


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.


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


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.


my hosting is still on 5.2.17 and are in the "security testing" phase of 5.3.


I wonder what they mean by security testing? What exactly are they testing and how? BTW given that there's no security patches released for 5.2 anymore (while bugs are still being found and published of course) - their understanding of security is certainly unorthodox.


I retract my security testing statement. The are currently testing if 5.3 is stable on their servers and have no ETA for the upgrade :-(. This was in mid October.


I think this is more about not pissing off random untechnical customers that haven't bothered to update their off the shelf blogging software since 2005. Guess the tipping point is when they are losing more customers not upgrading than they will upgrading.


> 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.


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.


Just an FYI, but they are at the end of their testing the RC of 5.4, so it should be declared stable in about 2-3 weeks.


Today, PHP 5.4 are released as stable.


Until it is ubiquitous, short syntax should still be used with caution.


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.


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.


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.


It really depends on what types of place you're working at. In the past 6 years or so, I've worked on a lot of PHP, and nearly all of it was pretty high-quality, because I don't like working at companies that don't care about code. My point is, if you have the luxury of the same filter in your job choices, PHP isn't necessarily the big red flag it could be.

The only exceptions for me have been when I've had to deal with someone else's codebase, or with Wordpress (and Django once), but again, I wouldn't personally take a job where those were the main responsibilities.


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.


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.


> 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.


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.


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.


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.


You probably have more experience with Wordpress than I do so I won't try to argue with that :).


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.


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


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


"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"


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.


Not exactly. Let's tweak your example to create a new object in your method.

  def foo s
    s = 'foo'
  end
  a = 'bar'
  foo a
  puts a
  # => bar
The assignment in the method doesn't change the object you "passed" in. Rather than passing by reference, think of Ruby as passing the value of a reference.

For more examples and explanation, see http://khelll.com/blog/ruby/ruby-pass-by-value-or-by-referen...


In python, strings are immutable as well.


Niether Ruby or Python do "pass by reference".

They both do "pass reference by value". Which is a big difference.


Here's a simpler comparison with way more langauges: http://rigaux.org/language-study/syntax-across-languages/Str...


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.


python will get you a job at google

I used Perl for all of my job interviews at Google, and I work at Google.

But Google is a Java and C++ company, with some Python around (but a bit of an anti-scripting culture as well).


ruby will get you a job at twitter.

I heard that twitter are moving from ruby to scala.


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.


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.


I too would like to get a reference for this. It sounds interesting, but it's the first I hear of it.


perl will get you a job running the internet ;)


I'm pretty sure the companies that you mentioned know enough about recruiting that they won't hire people solely based on the languages that they know. Skills transcend programming languages; especially among those similar-enough scripting languages.


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.


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.


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


Wish Lua was added to the list.

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


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.


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.


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


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


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/


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


PHP repl is actually php -a


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.


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.


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


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.


An increment/decrement operator is unary and doesn't give you the ability to change the value by any more than one.


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.


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.


Very helpful!! Like a quick & easy Rosetta stone


Very, very thorough. A great resource, thanks!


  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


Wait... there's more on the homepage! http://hyperpolyglot.org/


Nice. Useful and handy.


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.


[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.


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/


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?


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.


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.


I take it you spent more time writing your rant than actually navigating the site you're criticizing. Please take a look at the index.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: