Take the 2-minute tour ×

I'm planning to learn Perl 5 and as I have only used PHP until now, I wanted to know a bit about how the languages differ from each other.

As PHP started out as a set of "Perl hacks" it has obviously cloned some of Perls features.

  • What are the main differences in the syntax? Is it true that with Perl you have more options and ways to express something?

  • Why is Perl not used for dynamic websites very often anymore? What made PHP gain more popularity?

share|improve this question

closed as not constructive by Ja͢ck, gnat, Inbar Rose, sgarizvi, hauleth Mar 3 '13 at 9:29


Being curious, I have to ask: if you can freely choose your second language after PHP, why Perl instead of more modern Python or Ruby? –  jholster Mar 28 '10 at 22:45
What is the basis for Python and Ruby to be more modern? –  jpartogi Mar 28 '10 at 22:52
I don't think people should try to compare languages. It will only lead to confusion. –  Ben Shelock Mar 29 '10 at 2:23
@Ben: comparing syntax has limited utility. Comparing features can help in learning new languages. –  outis Mar 29 '10 at 4:10
I believe every language has its strength based on what the designers envisioned for it ; particularly based on a set of use cases. Therefore comparing languages is often bias and confusing –  CodeAngel Nov 23 '13 at 21:20

6 Answers 6

Perl and PHP are more different than alike. Let's consider Perl 5, since Perl 6 is still under development. Some differences, grouped roughly by subject:

  • Perl has native regular expression support, including regexp literals. PHP uses Perl's regexp functions as an extension.
  • Perl has quite a few more operators, including matching (=~, !~), quote-like (qw, qx &c.), exponentiation (**), string repetition (x) and range (.. and ...). PHP has a few operators Perl doesn't, such as the error suppression operator (@), instanceof (though Perl does have the Universal::isa method) and clone.
  • In PHP, new is an operator. In Perl, it's the conventional name of an object creation subroutine defined in packages, nothing special as far as the language is concerned.
  • Perl logical operators return their arguments, while they return booleans in PHP. Try:

    $foo = '' || 'bar';

    in each language. In Perl, you can even do $foo ||= 'default' to set $foo to a value if it's not already set. The shortest way of doing this in PHP is $foo = isset($foo) ? $foo : 'default';

  • Perl variable names indicate built-in type, of which Perl has three, and the type specifier is part of the name (called a "sigil"), so $foo is a different variable than @foo or %foo.
  • (related to the previous point) Perl has separate symbol table entries for scalars, arrays, hashes, code, file/directory handles and formats. Each has its own namespace.
  • Perl gives access to the symbol table, though manipulating it isn't for the faint of heart. In PHP, symbol table manipulation is limited to creating references and the extract function.
  • Note that "references" has a different meaning in PHP and Perl. In PHP, references are symbol table aliases. In Perl, references are smart pointers.
  • Perl has different types for integer-indexed collections (arrays) and string indexed collections (hashes). In PHP, they're the same type: an associative array/ordered map.
  • Perl arrays aren't sparse: setting an element with index larger than the current size of the array will set all intervening elements to undefined (see perldata). PHP arrays are sparse; setting an element won't set intervening elements.
  • Perl supports hash and array slices natively, and slices are assignable, which has all sorts of uses. In PHP, you use array_slice to extract a slice and array_splice to assign to a slice.
  • You can leave out the argument to the subscript operator in PHP for a bit of magic. In Perl, you can't leave out the subscript.
  • Perl hashes are unordered.
  • Perl has a large number of predefined and magic variables. PHP's predefined variables have quite a different purpose.
  • Perl has statement modifiers: some control statements can be placed at the end of a statement.
  • Perl supports dynamic scoping via the local keyword.
  • In addition, Perl has global, lexical (block), and package scope. PHP has global, function, object, class and namespace scope.
  • In Perl, variables are global by default. In PHP, variables in functions are local by default.
  • Perl supports explicit tail calls via the goto function.
  • Perl's prototypes provide more limited type checking for function arguments than PHP's type hinting. As a result, prototypes are of more limited utility than type hinting.
  • In Perl, the last evaluated statement is returned as the value of a subroutine if the statement is an expression (i.e. it has a value), even if a return statement isn't used. If the last statement isn't an expression (i.e. doesn't have a value), such as a loop, the return value is unspecified (see perlsub). In PHP, if there's no explicit return, the return value is NULL.
  • Perl flattens lists (see perlsub); for un-flattened data structures, use references.

    @foo = qw(bar baz);
    @qux = ('qux', @foo, 'quux'); # @qux is an array containing 4 strings
    @bam = ('bug-AWWK!', \@foo, 'fum'); # @bam contains 3 elements: two strings and a array ref

    PHP doesn't flatten arrays.

  • Perl has special code blocks (BEGIN, UNITCHECK, CHECK, INIT and END) that are executed. Unlike PHP's auto_prepend_file and auto_append_file, there is no limit to the number of each type of code block. Also, the code blocks are defined within the scripts, whereas the PHP options are set in the server and per-directory config files.
  • In Perl, the semicolon separates statements. In PHP, it terminates them, excepting that a PHP close tag ("?>") can also terminate a statement.
  • The value of expressions in Perl is context sensitive.
  • Negative subscripts in Perl are relative to the end of the array. $bam[-1] is the final element of the array. Negative subscripts in PHP are subscripts like any other.
  • In Perl 5, classes are based on packages and look nothing like classes in PHP (or most other languages). Perl 6 classes are closer to PHP classes, but still quite different. (Perl 6 is different from Perl 5 in many other ways, but that's off topic.) Many of the differences between Perl 5 and PHP arise from the fact that most of the OO features are not built-in to Perl but based on hacks. For example, $obj->method(@args) gets translated to something like (ref $obj)::method($obj, @args). Non-exhaustive list:
    • PHP automatically provides the special variable $this in methods. Perl passes a reference to the object as the first argument to methods.
    • Perl requires references to be blessed to create an object. Any reference can be blessed as an instance of a given class.
    • In Perl, you can dynamically change inheritance via the packages @ISA variable.
  • Perl supports operator overloading.
  • Strictly speaking, Perl doesn't have multiline comments, but the POD system can be used for the same affect.
  • In Perl, // is an operator. In PHP, it's the start of a one-line comment.
  • Until PHP 5.3, PHP had terrible support for anonymous functions (the create_function function) and no support for closures.
  • PHP had nothing like Perl's packages until version 5.3, which introduced namespaces.
  • Arguably, Perl's built-in support for exceptions looks almost nothing like exceptions in other languages, so much so that they scarcely seem like exceptions. You evaluate a block and check the value of $@ (eval instead of try, die instead of throw). The Error Try::Tiny module supports exceptions as you find them in other languages (as well as some other modules listed in Error's See Also section).

PHP was inspired by Perl the same way Phantom of the Paradise was inspired by Phantom of the Opera, or Strange Brew was inspired by Hamlet. It's best to put the behavior specifics of PHP out of your mind when learning Perl, else you'll get tripped up.

My brain hurts now, so I'm going to stop.

share|improve this answer
This is a fantastic answer, and I feel bad making such a tiny nitpick on it, but you're only mostly right about Perl arrays. When you have @array = qw(a b c) and you do $array[4] = 'e', the contents of the array aren't exactly ('a', 'b', 'c', undef, 'e'); they're ('a', 'b', 'c', nonexistent, 'e'). That is, the [3] slot doesn't hold a pointer to a scalar which is undef; it holds nothing at all (and the exists operator tests for this). A small difference, but a difference. :) –  hobbs Mar 30 '10 at 0:02
MAN, this is one of the BEST answers what I ever seen. Especially the part about the inspiration. Simply: cool and TRUE. ;) –  jm666 May 14 '11 at 17:57
Shortest way to set up a value to $foo if it's not already set may be isset($foo) || $foo='default'; –  Alexander V.B. Jan 17 '13 at 8:36
I wish I could give 100 upvote on this answer :) –  Alireza Fallah Jan 15 at 21:43

When PHP came to the scene, everyone were impressed with main differences from Perl:

  1. Input variables already in the global scope, no boring parsing.
  2. HTML embedding. Just <?php ... ?> anywhere. No boring templates.
  3. On-screen error messages. No boring error log peeks.
  4. Easy to learn. No boring book reading.

As the time passed, everyone learned that they were not a benefit, hehe...

share|improve this answer

I've noticed that most PHP vs. Perl pages seem to be of the

PHP is better than Perl because <insert lame reason here>

ilk, and rarely make reasonable comparisons.

Syntax-wise, you will find PHP is often easier to understand than Perl, particularly when you have little experience. For example, trimming a string of leading and trailing whitespace in PHP is simply

$string = trim($string);

In Perl it is the somewhat more cryptic


(I believe this is slightly more efficient than a single line capture and replace, and also a little more understandable.) However, even though PHP is often more English-like, it sometimes still shows its roots as a wrapper for low level C, for example, strpbrk and strspn are probably rarely used, because most PHP dabblers write their own equivalent functions for anything too esoteric, rather than spending time exploring the manual. I also wonder about programmers for whom English is a second language, as everybody is on equal footing with things such as Perl, having to learn it from scratch.

I have already mentioned the manual. PHP has a fine online manual, and unfortunately it needs it. I still refer to it from time to time for things that should be simple, such as order of parameters or function naming convention. With Perl, you will probably find you are referring to the manual a lot as you get started and then one day you will have an a-ha moment and never need it again. Well, at least not until you're more advanced and realize that not only is there more than one way, there is probably a better way, somebody else has probably already done it that better way, and perhaps you should just visit CPAN.

Perl does have a lot more options and ways to express things. This is not necessarily a good thing, although it allows code to be more readable if used wisely and at least one of the ways you are likely to be familiar with. There are certain styles and idioms that you will find yourself falling into, and I can heartily recommend reading Perl Best Practices (sooner rather than later), along with Perl Cookbook, Second Edition to get up to speed on solving common problems.

I believe the reason Perl is used less often in shared hosting environments is that historically the perceived slowness of CGI and hosts' unwillingness to install mod_perl due to security and configuration issues has made PHP a more attractive option. The cycle then continued, more people learned to use PHP because more hosts offered it, and more hosts offered it because that's what people wanted to use. The speed differences and security issues are rendered moot by FastCGI these days, and in most cases PHP is run out of FastCGI as well, rather than leaving it in the core of the web server.

Whether or not this is the case or there are other reasons, PHP became popular and a myriad of applications have been written in it. For the majority of people who just want an entry-level website with a simple blog or photo gallery, PHP is all they need so that's what the hosts promote. There should be nothing stopping you from using Perl (or anything else you choose) if you want.

At an enterprise level, I doubt you would find too much PHP in production (and please, no-one point at Facebook as a counter-example, I said enterprise level).

share|improve this answer
Would the down-voter care to explain why? –  Duncan Mar 29 '10 at 4:29
Happily, it is becoming easier to get hosting with FastCGI hosting which gives decent performance without the complications of mod_perl. –  Quentin Mar 29 '10 at 5:34
@David Dorward: Okay. I was speaking in a historical sense, since FastCGI also gives better performance/security than mod_php. I'll edit that to try and make it a bit clearer. –  Duncan Mar 29 '10 at 5:49
Your trim example doesn't make sense. Whats better 4 operators or remembering all of the inconsistent parameters and return values of all the PHP functions such as ereg ereg_replace eregi eregi_replace mb_ereg mb_ereg_replace mb_eregi mb_eregi_replace preg_match preg_match_all preg_replace str_replace str_ireplace strstr stristr strrchr strpos stripos strrpos strripos mb_strpos mb_strrpos –  Myforwik Mar 25 '13 at 2:34
Your Perl trim example could be much simpler: $str =~ s/^\s+|\s+$//g; –  Francisco Zarabozo Jul 22 at 8:09

Perl is used plenty for websites, no less than Python and Ruby for example. That said, PHP is used way more often than any of those. I think the most important factors in that are PHP's ease of deployment and the ease to start with it.

The differences in syntax are too many to sum up here, but generally it is true that it has more ways to express yourself (this is know as TIMTWOTDI, There Is More Than One Way To Do It).

share|improve this answer

My favorite thing about Perl is the way it handles arrays/lists. Here's an example of how you would make and use a Perl function (or "subroutine"), which makes use of this for arguments:

sub multiply
    my ($arg1, $arg2) = @_; # @_ is the array of arguments
    return $arg1 * $arg2;

In PHP you could do a similar thing with list(), but it's not quite the same; in Perl lists and arrays are actually treated the same (usually). You can also do things like:

$week_day_name = ("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")[$week_day_index];

And another difference that you MUST know about, is numerical/string comparison operators. In Perl, if you use <, >, ==, !=, <=>, and so on, Perl converts both operands to numbers. If you want to convert as strings instead, you have to use lt, gt, eq, ne, cmp (the respective equivalents of the operators listed previously). Examples where this will really get you:

if ("a" == "b") { ... } # This is true.
if ("a" == 0) { ... } # This is also true, for the same reason.
share|improve this answer
Arrays and lists are usually treated the same. –  Brad Gilbert Mar 29 '10 at 3:52
Yes, true. I think I was going to say that, but forgot. Edited to reflect that. –  crimson_penguin Mar 29 '10 at 4:04

I do not need add anything to outis's fantastic answer, i want only show the answer for you question:

Why is Perl not used for dynamic websites very often anymore? What made PHP gain more popularity than it?

Please check first some "Job Trends" sites - and you can make the judgement alone.

as you can see, perl is still a leader - but preferable for real applications not for toys. :)

share|improve this answer
I think this comparison is also interesting: www.simplyhired.com/a/jobtrends/trend/q-Perl,+Python,+PHP,+Ruby,+Java,+C%23,+C –  Sorin Postelnicu Dec 26 '12 at 20:41
