Perl 和 PHP 的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2534756/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 06:52:35  来源:igfitidea点击:

Differences between Perl and PHP

phpperl

提问by lok

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.

我打算学习 Perl 5,因为到目前为止我只使用过 PHP,所以我想了解一下这些语言之间的区别。

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

当 PHP 开始时是一组“Perl hacks”,它显然克隆了一些 Perls 功能。

  • 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?

  • 语法的主要区别是什么?使用 Perl,您真的有更多的选择和表达方式吗?

  • 为什么 Perl 不再经常用于动态网站?是什么让 PHP 越来越受欢迎?

回答by outis

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 和 PHP 有很大的不同。让我们考虑 Perl 5,因为 Perl 6 仍在开发中。一些差异,大致按主题分组:

  • 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::isamethod) and clone.
  • In PHP, newis an operator. In Perl, it's the conventional name of an object creation subroutinedefined in packages, nothing special as far as the language is concerned.
  • Perl logical operators return their arguments, while they return booleansin 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';(Update, in PHP 7.0+ you can do $foo = $foo ?? 'default')

  • Perl variable namesindicate built-in type, of which Perl has three, and the type specifier is part of the name (called a "sigil"), so $foois a different variable than @fooor %foo.
  • (related to the previous point) Perl has separate symbol tableentries 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 referencesand the extractfunction.
  • Note that "references" has a different meaning in PHP and Perl. In PHP, referencesare symbol table aliases. In Perl, referencesare 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 slicesnatively, and slices are assignable, which has all sorts of uses. In PHP, you use array_sliceto extract a slice and array_spliceto assign to a slice.
  • You can leave out the argument to the subscript operatorin 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 variableshave quite a different purpose.
  • Perl has statement modifiers: some control statements can be placed at the end of a statement.
  • Perl supports dynamic scopingvia the localkeyword.
  • 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 callsvia the gotofunction.
  • Perl's prototypesprovide 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, INITand END) that are executed. Unlike PHP's auto_prepend_fileand 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 terminatesthem, 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 differentfrom 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 $thisin methods. Perl passes a reference to the object as the first argument to methods.
    • Perl requires references to be blessedto 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 @ISAvariable.
  • Perl supports operator overloading.
  • Strictly speaking, Perl doesn't have multiline comments, but the PODsystem 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_functionfunction) 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 $@(evalinstead of try, dieinstead of throw). The ErrorTry::Tinymodule supports exceptions as you find them in other languages (as well as some other modules listed in Error's See Alsosection).
  • Perl 具有本机正则表达式支持,包括正则表达式文字。PHP 使用 Perl 的 regexp 函数作为扩展。
  • Perl 有更多的运算符,包括匹配( =~, !~)、类引号( qw, qx&c.)、取幂( **)、字符串重复( x) 和范围( ..and ...)。PHP 有一些 Perl 没有的操作符,例如错误抑制操作符( @)、instanceof(尽管 Perl 有Universal::isa方法)和clone.
  • 在 PHP 中,new是一个运算符。在 Perl 中,它是在包中定义的对象创建子例程的常规名称,就语言而言没有什么特别之处。
  • Perl 逻辑运算符返回它们的参数,而它们在 PHP 中返回布尔值。尝试:

    $foo = '' || 'bar';
    

    在每种语言中。在 Perl 中,您甚至$foo ||= 'default'可以将 $foo 设置为尚未设置的值。在 PHP 中执行此操作的最短方法是$foo = isset($foo) ? $foo : 'default';(更新,在 PHP 7.0+ 中您可以执行$foo = $foo ?? 'default'

  • Perl变量名表示内置类型,其中 Perl 有三个,类型说明符是名称的一部分(称为“符号”),因此$foo是与@fooor不同的变量%foo
  • (与上一点相关)Perl为标量、数组、散列、代码、文件/目录句柄和格式提供了单独的符号表条目。每个都有自己的命名空间。
  • Perl 允许访问符号表,但操作它并不适合胆小的人。在 PHP 中,符号表操作仅限于创建引用extract函数。
  • 请注意,“引用”在 PHP 和 Perl 中具有不同的含义。在 PHP 中,引用是符号表别名。在 Perl 中,引用是智能指针。
  • Perl 对整数索引集合(数组)和字符串索引集合(散列)有不同的类型。在 PHP 中,它们是相同的类型:关联数组/有序映射
  • Perl 数组不是稀疏的:设置索引大于数组当前大小的元素会将所有中间元素设置为undefined(请参阅perldata)。PHP 数组是稀疏的;设置元素不会设置中间元素。
  • Perl本身支持散列和数组切片,并且切片是可分配的,具有各种用途。在 PHP 中,您用于array_slice提取切片并array_splice分配给切片。
  • 您可以在 PHP 中省略下标运算符参数以获得一些魔法。在 Perl 中,您不能省略下标。
  • Perl 哈希是无序的
  • Perl 有大量的预定义和魔法变量。PHP 的预定义变量具有完全不同的用途。
  • Perl 有语句修饰符:一些控制语句可以放在语句的末尾。
  • Perl通过关键字支持动态范围local
  • 此外,Perl 具有全局、词法(块)和包作用域。PHP 具有全局、函数、对象、类和命名空间作用域
  • 在 Perl 中,变量默认是全局的。在 PHP 中,函数中的变量默认是局部的。
  • Perl通过该函数支持显式尾调用goto
  • Perl 的原型为函数参数提供了比 PHP 的类型提示更有限的类型检查。因此,原型比类型提示的效用更有限。
  • 在 Perl 中,如果语句是一个表达式(即它有一个值),即使没有使用 return 语句,最后评估的语句也会作为子例程的值返回。如果最后一条语句不是表达式(即没有值),例如循环,则返回值是未指定的(请参阅perlsub)。在 PHP 中,如果没有显式返回,则返回值为 NULL
  • Perl 扁平化列表(参见perlsub);对于未展平的数据结构,请使用引用。

    @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 不会展平数组。

  • Perl有特殊代码块BEGINUNITCHECKCHECKINITEND),其被执行。与 PHP 的auto_prepend_fileand不同auto_append_file,每种类型的代码块的数量没有限制。此外,代码块在脚本中定义,而 PHP 选项在服务器和每个目录的配置文件中设置。
  • 在 Perl 中,分号分隔语句。在 PHP 中,它终止它们,除了 PHP 结束标记(“?>”)也可以终止一个语句。
  • Perl 中表达式的值是上下文敏感的
  • Perl 中的负下标相对于数组的末尾。$bam[-1]是数组的最后一个元素。PHP 中的负下标和其他下标一样。
  • 在 Perl 5 中,类基于包,看起来与 PHP(或大多数其他语言)中的类完全不同。Perl 6 类更接近于 PHP 类,但仍然有很大的不同。(Perl 6的是不同的在其他许多方面,从Perl 5中,但是这是题外话。)许多的Perl 5和PHP之间的差异的事实,大多数OO功能没有内置于Perl的,但基于黑客引起。例如,$obj->method(@args)被翻译成类似(ref $obj)::method($obj, @args). 非详尽清单:
    • PHP 自动$this在方法中提供特殊变量。Perl 将对象的引用作为方法的第一个参数传递。
    • Perl 要求引用被祝福以创建对象。任何引用都可以被祝福为给定类的实例。
    • 在 Perl 中,您可以通过包@ISA变量动态更改继承。
  • Perl 支持运算符重载
  • 严格来说,Perl 没有多行注释,但POD系统可以用于相同的效果。
  • 在 Perl 中,//是一个运算符。在 PHP 中,它是单行注释的开始。
  • 在 PHP 5.3 之前,PHP 对匿名函数(create_function函数)的支持非常糟糕,并且不支持闭包。
  • PHP 没有像 Perl 的包那样直到 5.3 版,它引入了namespaces
  • 可以说,Perl 对异常的内置支持与其他语言中的异常几乎完全不同,以至于它们几乎不像异常。您评估一个块并检查$@(eval而不是trydie而不是throw) 的值。该错误尝试::微小的,你发现他们在其他语言模块支持异常(以及在列出的一些其他模块错误的另请参见部分)。

PHP was inspired by Perl the same way Phantom of the Paradisewas inspired by Phantom of the Opera, or Strange Brewwas 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.

PHP 受到 Perl 的启发,就像Phantom of the Paradise受到Phantom of the Opera 的启发,或者Strange Brew受到Hamlet 的启发一样。最好在学习 Perl 时将 PHP 的行为细节抛诸脑后,否则你会被绊倒。

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

我的脑子现在很痛,所以我要停下来。

回答by Your Common Sense

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

当 PHP 出现时,每个人都对与 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.
  1. 输入变量已经在全局作用域内,没有枯燥的解析。
  2. HTML 嵌入。就<?php ... ?>在任何地方。没有无聊的模板。
  3. 屏幕上的错误消息。没有无聊的错误日志偷看。
  4. 简单易学。没有无聊的书阅读。

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

时间久了,大家才知道自己不是福利,呵呵……

回答by Duncan

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

我注意到大多数 PHP 与 Perl 页面似乎都属于

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

PHP 比 Perl 好,因为 <在这里插入蹩脚的原因>

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

在语法方面,您会发现 PHP 通常比 Perl 更容易理解,尤其是当您几乎没有经验时。例如,在 PHP 中修剪一串前导和尾随空格很简单

$string = trim($string);

In Perl it is the somewhat more cryptic

在 Perl 中,它有点神秘

$string =~ s/^\s+//;
$string =~ s/\s+$//;

(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, strpbrkand strspnare 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.

(我相信这比单行捕获和替换更有效,也更容易理解。)然而,尽管 PHP 通常更像英语,但它有时仍然显示其根源是低级 C 的包装器,例如,strpbrk并且strspn可能很少使用,因为大多数 PHP 爱好者会为任何太深奥的东西编写自己的等效函数,而不是花时间浏览手册。我也想知道那些将英语作为第二语言的程序员,因为每个人都与 Perl 之类的东西处于同等地位,必须从头开始学习。

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 lotas you get started and then one day you will have an a-hamoment 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.

我已经提到了手册。PHP 有一个很好的在线手册,不幸的是它需要它。对于应该简单的事情,例如参数顺序或函数命名约定,我仍然会时不时地引用它。用Perl,你可能会发现你指的是手动一个不少,你上手,然后有一天,你将有一公顷的时刻,再也不需要它。好吧,至少在您更高级并意识到不仅有不止一种方法,而且可能有更好的方法之前,至少不会这样做,其他人可能已经这样做了,也许您应该访问 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 Editionto get up to speed on solving common problems.

Perl 确实有更多的选择和表达方式。这不一定是一件好事,尽管如果明智地使用它并且至少是您可能熟悉的一种方式,它可以使代码更具可读性。您会发现自己会陷入某些风格和习惯用法,我衷心建议您阅读Perl Best Practices(宜早不宜迟)以及Perl Cookbook, Second Edition,以加快解决常见问题的速度。

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_perldue 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 FastCGIthese days, and in most cases PHP is run out of FastCGI as well, rather than leaving it in the core of the web server.

我相信 Perl 在共享主机环境中使用较少的原因是,从历史上看,CGI 的感知缓慢以及主机由于安全和配置问题而不愿意安装mod_perl使 PHP 成为更具吸引力的选择。然后循环继续,更多的人学习使用 PHP,因为更多的主机提供它,更多的主机提供它,因为这是人们想要使用的。如今,FastCGI使速度差异和安全问题变得毫无意义,而且在大多数情况下,PHP 也会用完 FastCGI,而不是将其留在 Web 服务器的核心中。

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.

无论是这种情况还是其他原因,PHP 变得流行起来,并且已经用它编写了无数的应用程序。对于大多数只想要一个带有简单博客或照片库的入门级网站的人来说,PHP 就是他们所需要的,所以这就是主机所宣传的。如果您愿意,应该没有什么能阻止您使用 Perl(或您选择的任何其他东西)。

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

在企业级别,我怀疑您会发现生产中的 PHP 过多(请不要在Facebook举个反例,我说的是企业级别)。

回答by crimson_penguin

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:

我最喜欢 Perl 的地方是它处理数组/列表的方式。这是一个如何创建和使用 Perl 函数(或“子例程”)的示例,该函数将 this 用作参数:

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:

在 PHP 中,您可以使用 做类似的事情list(),但并不完全相同;在 Perl 中,列表和数组实际上被视为相同(通常)。您还可以执行以下操作:

$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:

您必须了解的另一个区别是数字/字符串比较运算符。在 Perl 中,如果您使用<, >, ==, !=, <=>, 等等,Perl 会将两个操作数都转换为数字。如果您想转换为字符串,则必须使用lt, gt, eq, ne, cmp(前面列出的运算符的相应等效项)。这将真正让您受益的示例:

if ("a" == "b") { ... } # This is true.
if ("a" == 0) { ... } # This is also true, for the same reason.

回答by Leon Timmermans

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.

Perl 被大量用于网站,例如不亚于 Python 和 Ruby。也就是说,PHP 的使用频率比任何一种都多。我认为其中最重要的因素是 PHP 易于部署和易于启动。

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

语法上的差异太多了,无法在这里总结,但总的来说,它确实有更多的方式来表达自己(这就是众所周知的 TIMTWOTDI,有不止一种方法可以做到)。

回答by jm666

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

我不需要在 outis 的精彩答案中添加任何内容,我只想显示您问题的答案:

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

为什么 Perl 不再经常用于动态网站?是什么让 PHP 比它更受欢迎?

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

如您所见,perl 仍然是领先者——但更适合实际应用而不是玩具。:)