# [X分鐘速成Y](http://learnxinyminutes.com/)
## 其中 Y=perl
源代碼下載:?[learnperl-cn.pl](http://learnxinyminutes.com/docs/files/learnperl-cn.pl)
Perl 5是一個功能強大、特性齊全的編程語言,有25年的歷史。
Perl 5可以在包括便攜式設備和大型機的超過100個平臺上運行,既適用于快速原型構建,也適用于大型項目開發。
~~~
# 單行注釋以#號開頭
#### Perl的變量類型
# 變量以$號開頭。
# 合法變量名以英文字母或者下劃線起始,
# 后接任意數目的字母、數字或下劃線。
### Perl有三種主要的變量類型:標量、數組和哈希。
## 標量
# 標量類型代表單個值:
my $animal = "camel";
my $answer = 42;
# 標量類型值可以是字符串、整型或浮點類型,Perl會根據需要自動進行類型轉換。
## 數組
# 數組類型代表一列值:
my @animals = ("camel", "llama", "owl");
my @numbers = (23, 42, 69);
my @mixed = ("camel", 42, 1.23);
## 哈希
# 哈希類型代表一個鍵/值對的集合:
my %fruit_color = ("apple", "red", "banana", "yellow");
# 可以使用空格和“=>”操作符更清晰的定義哈希:
my %fruit_color = (
apple => "red",
banana => "yellow",
);
# perldata中有標量、數組和哈希更詳細的介紹。 (perldoc perldata).
# 可以用引用構建更復雜的數據類型,比如嵌套的列表和哈希。
#### 邏輯和循環結構
# Perl有大多數常見的邏輯和循環控制結構
if ( $var ) {
...
} elsif ( $var eq 'bar' ) {
...
} else {
...
}
unless ( condition ) {
...
}
# 上面這個比"if (!condition)"更可讀。
# 有Perl特色的后置邏輯結構
print "Yow!" if $zippy;
print "We have no bananas" unless $bananas;
# while
while ( condition ) {
...
}
# for和foreach
for ($i = 0; $i <= $max; $i++) {
...
}
foreach (@array) {
print "This element is $_\n";
}
#### 正則表達式
# Perl對正則表達式有深入廣泛的支持,perlrequick和perlretut等文檔有詳細介紹。簡單來說:
# 簡單匹配
if (/foo/) { ... } # 如果 $_ 包含"foo"邏輯為真
if ($a =~ /foo/) { ... } # 如果 $a 包含"foo"邏輯為真
# 簡單替換
$a =~ s/foo/bar/; # 將$a中的foo替換為bar
$a =~ s/foo/bar/g; # 將$a中所有的foo替換為bar
#### 文件和輸入輸出
# 可以使用“open()”函數打開文件用于輸入輸出。
open(my $in, "<", "input.txt") or die "Can't open input.txt: $!";
open(my $out, ">", "output.txt") or die "Can't open output.txt: $!";
open(my $log, ">>", "my.log") or die "Can't open my.log: $!";
# 可以用"<>"操作符讀取一個打開的文件句柄。 在標量語境下會讀取一行,
# 在列表環境下會將整個文件讀入并將每一行賦給列表的一個元素:
my $line = <$in>;
my @lines = <$in>;
#### 子程序
# 寫子程序很簡單:
sub logger {
my $logmessage = shift;
open my $logfile, ">>", "my.log" or die "Could not open my.log: $!";
print $logfile $logmessage;
}
# 現在可以像內置函數一樣調用子程序:
logger("We have a logger subroutine!");
~~~
#### 使用Perl模塊
Perl模塊提供一系列特性來幫助你避免重新發明輪子,CPAN是下載模塊的好地方( http://www.cpan.org/ )。Perl發行版本身也包含很多流行的模塊。
perlfaq有很多常見問題和相應回答,也經常有對優秀CPAN模塊的推薦介紹。
#### 深入閱讀
- [perl-tutorial](http://perl-tutorial.org/)
- [www.perl.com的learn站點](http://www.perl.org/learn.html)
- [perldoc](http://perldoc.perl.org/)
- 以及 perl 內置的: `perldoc perlintro`