en: =head1 Learn Perl in about 2 hours 30 minutes
cn: =head1 在两个小时30分钟内了解 Perl
en: =head2 By Sam Hughes
cn: =head2 作者 Sam Hughes
en: Perl is a dynamic, dynamically-typed, high-level, scripting (interpreted) language most comparable with PHP and Python. Perl's syntax owes a lot to ancient shell scripting tools, and it is famed for its overuse of confusing symbols, the majority of which are impossible to Google for. Perl's shell scripting heritage makes it great for writing glue code: scripts which link together other scripts and programs.
cn: Perl语言是一门高级解释型动态语言,它的许多数据类型是运行时才决定的,并且经常和PHP和Python相提并论。Perl 从古老的Shell脚本语言中借鉴了许多语法特性,因为被过度使用的各种奇怪符号而声名狼藉,而且大部分代码借助Google的搜索功能都不能明白。Perl语言因其来自Shell的语言特性使之成为一门好用的胶水语言: 将其他语言和各种脚本连接在一起共同工作。
en: Perl is ideally suited for processing text data and producing more text data. Perl is widespread, popular, highly portable and well-supported. Perl was designed with the philosophy "There's More Than One Way To Do It" (TMTOWTDI) (contrast with Python, where "there should be one - and preferably only one - obvious way to do it").
cn: Perl 语言非常适合处理文本,并生成更多的文本。Perl语言应用广泛,流行,可移植性极佳,而且有良好的社区支持。Perl 语言的设计哲学是:"每个问题都有许多解决方式"(TMTOWTDI)( 与之相反,Python 的设计哲学是:每个问题应该只有一种,而且只有一种明确的,最好的解决方式)。
en: Perl has horrors, but it also has some great redeeming features. In this respect it is like every other programming language ever created.
cn: Perl 有令人沮丧的地方,但同时也有许多奇妙的特性。从这一点来看,它同其他任何一种曾经有过的编程语言一样。
en: This document is intended to be informative, not evangelical. It is aimed at people who, like me: dislike the official Perl documentation at http://perl.org/ for being intensely technical and giving far too much space to very unusual edge cases learn new programming languages most quickly by "axiom and example" wish Larry Wall would get to the point already know how to program in general terms don't care about Perl beyond what's necessary to get the job done.
cn: 这篇文章只是提供一些知识,并不是什么宣传广告,目标读者只是针对像我这样的人: 厌恶 http://perl.org 上面学术性的文档,那些东西只会长篇累牍的讲述一些永远用不到的边缘问题。我只想通过一些通用规则和实例快速了解那些从Larry Wall的角度永远都不关心的基础编程问题,并学些能帮我找到一份工作的基础知识。
en: This document is intended to be as short as possible, but no shorter.
cn: 这篇文档的目的是用短的不能再短的形式来讲:
en: =head2 Preliminary notes
cn: =head2 研究初探
en: The following can be said of almost every declarative statement in this document: "that's not, strictly speaking, true; the situation is actually a lot more complicated". If you see a serious lie, point it out, but I reserve the right to preserve certain critical lies-to-children.
cn: 以下声明针对整个文档:“这并不是绝对的,实际情况要复杂的多”。你如果发现一个严重错误,请告诉我。但我保留对孩子们说错话的权利。
en: Throughout this document I'm using example print statements to output data but not explicitly appending line breaks. This is done to prevent me from going crazy and to give greater attention to the actual string being printed in each case, which is invariably more important. In many examples, this results in alotofwordsallsmusheduptogetherononeline if the code is run in reality. Try to ignore this.
cn: 在本文档中,我在实例中打印状态,输出数据,但没有明确的追加换行符。这样做是为了避免我发狂,让我能集中精力在实例中字符串的输出,我相信这是更重要的。在许多例子中,实际的输出可能是 "alotofwordsallsmusheduptogetherononeline". 请不要在意。
en: =head2 Hello world
cn: =head2 Hello world
en: A Perl script is a text file with the extension .pl.
cn: 一个 Perl 脚本就是一个后缀为 .pl 的文本文件。
en: Here's the full text of helloworld.pl:
cn: 这就是 helloworld.pl 的全文:
use strict;
use warnings;
print "Hello world";
en: Perl scripts are interpreted by the Perl interpreter, perl or perl.exe:
cn: Perl 脚本被 Perl 的解释器来解释运行:
perl helloworld.pl [arg0 [arg1 [arg2 ...]]]
en: A few immediate notes. Perl's syntax is highly permissive and it will allow you to do things which result in ambiguous-looking statements with unpredictable behaviour. There's no point in me explaining what these behaviours are, because you want to avoid them.
cn: 说实话,Perl 的语法非常宽容,他可以替你预测一些模糊的不知所云的代码的行为,我实在不想讲这些东西,因为你们应当竭力避免这么做。
en: The way to avoid them is to put use strict; use warnings; at the very top of every Perl script or module that you create. Statements of the form use foo; are pragmas. A pragma is a signal to perl.exe, which takes effect when initial syntactic validation is being performed, before the program starts running. These lines have no effect when the interpreter encounters them at run time.
cn: 避免这么做的方法就是将 'use strict; use warnings' 放置在每一个脚本或模块的最前面。'use foo' 这样的语句是编译提示,编译提示是给 Perl.exe 的信号,在程序运行前,对解释器初始化语法验证规则施加影响。在代码运行的时候,解释器将忽略这些东西。
en: The symbol # begins a comment. A comment lasts until the end of the line. Perl has no block comment syntax.
cn: '#' 符号是一个注释的开始。注释的结束是到行的末尾。Perl 没有针对块的注释语法。
en: =head2 Variables
cn: =head2 变量
en: Perl variables come in three types: scalars, arrays and hashes. Each type has its own sigil: $, @ and % respectively. Variables are declared using my, and remain in scope until the end of the enclosing block or file.
cn: Perl 的变量有三种类型:标量,数组和散列。每种类型都有自己的前置符号:$, @ 和 % 分别代表这三种类型。变量使用 my 来声明,有效范围在闭合块范围内或到文件的末尾。
en: =head3 Scalar variables
cn: 标量变量
en: A scalar variable can contain:
cn: 一个标量变量可以包含:
=over 4
en: =item * undef (corresponds to None in Python, null in PHP)
cn: =item * undef (相当于 Python 中的 None, PHP 中的 null)
en: =item * a number (Perl does not distinguish between an integer and a float)
cn: =item * 一个数字( Perl 并不区分一个整型数字和浮点数字)
en: =item * a string
cn: =item * 一个字符串
en: =item * a reference to any other variable.
cn: =item * 一个指向别的变量的引用
=back
my $undef = undef;
print $undef; # prints the empty string "" and raises a warning
# implicit undef:
my $undef2;
print $undef2; # prints "" and raises exactly the same warning
my $num = 4040.5;
print $num; # "4040.5"
my $string = "world";
print $string; # "world"
en: (References are coming up shortly.)
cn: (稍后介绍引用)
en: String concatenation using the . operator (same as PHP):
cn: 字符串使用 '.' 进行连接(和PHP一样)
print "Hello ".$string; # "Hello world"
en: =head3 Booleans
cn: =head3 布尔值
en: Perl has no boolean data type. A scalar in an if statement evaluates to boolean "false" if and only if it is one of the following:
cn: Perl 没有布尔数据类型。只有如下几种值才能在 if 判断语句中返回 'false' :
=over 4
en: =item * undef
cn: =item * undef
en: =item * number 0
cn: =item * 数字 0
en: =item * string ""
cn: =item * 字符串 ""
en: =item * string "0"
cn: =item * 字符串 "0"
=back
en: The Perl documentation repeatedly claims that functions return "true" or "false" values in certain situations. In practice, when a function is claimed to return "true" it usually returns 1, and when it is claimed to return false it usually returns the empty string, "".
cn: Perl 文档中经常提到函数在某些情况下会返回 'true' 或 'false'. 实际上,函数通常用 'return 1' 来返回真,用返回空字符串 '' 来表示返回假。
Since a hash has no underlying order, the keys may be returned in any order. Use the sort built-in function to sort the array of keys alphabetically beforehand:
因为一个散列并没有顺序,键值可能在按任何顺序返回。使用排序内置函数事先按字母顺序排序数组的键:
foreach my $key (sort keys %scientists) {
print $key, ": ", $scientists{$key};
}
如果你不提供显式迭代器,Perl使用一个默认的迭代器,$ _。$ _内置变量:
foreach ( @array ) {
print $_;
}
如果使用默认的迭代器,你只希望把单个语句内部循环,您可以使用超短循环语法:
print $_ foreach @array;
循环控制
next and last can be used to control the progress of a loop. In most programming languages these are known as continue and break respectively. We can also optionally provide a label for any loop. By convention, labels are written in ALLCAPITALS. Having labelled the loop, next and last may target that label. This example finds primes below 100:
grep and map may be combined to form list comprehensions, an exceptionally powerful feature conspicuously absent from many other programming languages.
$a and $b are always scalars, but they can be references to quite complex objects which are difficult to compare. If you need more space for the comparison, you can create a separate subroutine and provide its name instead:
Notice how the subroutine and block are never explicitly provided with $a and $b. Like $_, $a and $b are, in fact, global variables which are populated with a pair of values to be compared each time.
注意,子程序和块是从来没有明确地提供$a和$b。就像变量$ _, $ a和$b事实上是全局变量。
复制代码
作者: shijiang1130 时间: 2013-03-07 00:12
内置函数
By now you have seen at least a dozen built-in functions: print, sort, map, grep, keys, scalar and so on. Built-in functions are one of Perl's greatest strengths. They
my $newString = ($_[2] x ($_[1] - length $_[0])) . $_[0];
return $newString;
}
第二种方式,仅解开参数
sub left_pad {
my $oldString = $_[0];
my $width = $_[1];
my $padChar = $_[2];
my $newString = ($padChar x ($width - length $oldString)) . $oldString;
return $newString;
}
3。通过删除数据取出@ _,推荐使用转变为最多4个参数:
sub left_pad {
my $oldString = shift @_;
my $width = shift @_;
my $padChar = shift @_;
my $newString = ($padChar x ($width - length $oldString)) . $oldString;
return $newString;
}
If no array is provided to the shift function, then it operates on @_ implicitly. This approach is seen very commonly:
如果没有数组提供给shift函数,那么@_作为隐式的提供。这种方法被认为非常普遍:
sub left_pad {
my $oldString = shift;
my $width = shift;
my $padChar = shift;
my $newString = ($padChar x ($width - length $oldString)) . $oldString;
return $newString;
}
复制代码
作者: shijiang1130 时间: 2013-03-07 13:31
超出4个参数难以追踪哪些正被分配的地方。
你可以解压的@ _去使用多个同时标量赋值。这是允许最多4个参数:
sub left_pad {
my ($oldString, $width, $padChar) = @_;
my $newString = ($padChar x ($width - length $oldString)) . $oldString;
return $newString;
}
5. For subroutines with large numbers of arguments or where some arguments are optional or cannot be used in combination with others, best practice is to require the user to provide a hash of arguments when calling the subroutine, and then unpack @_ back into that hash of arguments. For this approach, our subroutine call would look a little different:
The system function can be used to invoke another program with the arguments listed. The value returned by system is the same value with which $? is populated:
系统功能可用于调用另一个程序的参数列。系统通过$ ?返回的:
my $rc = system "perl", "anotherscript. pl", "foo", "bar", "baz";
Note that chomp acts on $line in place. $line = chomp $line is probably not what you want.
注意,chomp的用法。$line= chomp $line不是你想要的结果。
您还可以使用eof检测是否已经达到文件的末尾:
while(! eof $fh) {
my $line = readline $fh;
# process $line...
}
But beware of just using while(my $line = readline $fh), because if $line turns out to be "0", the loop will terminate early. If you want to write something like that, Perl provides the <> operator which wraps up readline in a fractionally safer way. This is very commonly-seen and perfectly safe:
Once the Perl module is created and perl knows where to look for it, you can use the require built-in function to search for and execute it during a Perl script. For example, calling require Demo::StringUtils causes the Perl interpreter to search each directory listed in PERL5LIB in turn, looking for a file called Demo/StringUtils.pm. After the module has been executed, the subroutines that were defined there suddenly become available to the main script. Our example script might be called main. pl and read as follows:
A package is a namespace in which subroutines can be declared. Any subroutine you declare is implicitly declared within the current package. At the beginning of execution, you are in the main package, but you can switch package using the package built-in function:
•In =~ m// and =~ s/// operations, you can use braces instead of slashes as the regex delimiters. This is quite useful if your regex contains a lot of slashes, which would otherwise need escaping with backslashes. For example, =~ m{///} matches three literal forward slashes, and =~ s{^https? ://}{} removes the protocol part of a URL.
•在= ~ m / /和= ~ s / / /操作,您可以使用括号代替斜杠分隔符的正则表达式。这是非常有用的,如果你的正则表达式包含大量的斜杠,否则需要与反斜杠转义。例如,= ~ m { / / / }匹配三个字面斜杠,{ ^ = ~年代https吗?:/ / } { }解除协议的一部分,一个URL。
•Perl does have CONSTANTS. These are discouraged now, but weren't always. Constants are actually just subroutine calls with omitted brackets.
•Perl确实有常量。这些是气馁了,但不总是。常数实际上只是子程序调用与省略括号。
•Sometimes people omit quotes around hash keys, writing $hash{key} instead of $hash{"key"}. They can get away with it because in this situation the bareword key occurs as the string "key", as opposed to a subroutine call key().