- 浏览: 4594400 次
- 性别:
- 来自: 武汉
文章分类
最新评论
-
x70740692:
我也是舆情系统苦逼难做
网络舆情信息分析系统——(1) -
勇气魄力:
啥啊!没什么信息
ArcGIS for Server 10.1智能支持云的架构(上) -
迟来的风:
很不错,值得学习,非常感谢您给了我们这么好的资源
最新 跟我学spring3 电子书下载 -
linfanne:
哭了, 有一个地方写错了, 跟了2个多小时代码才找到原因& ...
Spring MVC+Freemarker+Javascript的多语言(国际化i18n/本地化)和主题(Theme)实现 -
linfanne:
无数的鲜花,多语言暂时不考虑,多主题刚好用到,我一般都不回帖, ...
Spring MVC+Freemarker+Javascript的多语言(国际化i18n/本地化)和主题(Theme)实现
Perl的基本語法(转)
本文转自http://ind.ntou.edu.tw/~dada/cgi/Perlsynx.htm
前言:
這篇文章是花了我很多時間、費了我很多心血才完成的,雖然連我自己都覺得無法達到盡善盡美的境界,但希望能幫助大家入門,稍微了解到Perl到底是個什麼樣的東西,Perl到底有那些強大的功能,那麼這篇文章的目的就達到了。
我分做資料型態、控制敘述、副程式、I/O和檔案處理、Regular Expressions、Spectial Variables、Help
這幾部分來講解,但只是敘述了一些Perl的基本語法而已,Perl活潑的特性和程式的技巧就無法一一詳述了,甚為缺憾。
(1) 資料型態(Data type):
Perl的資料型態大致分為四種:Scalar、Scalar Array、Hash Array、References,
看起來雖少但用起來卻綽綽有餘。尤其在寫Perl程式時可以不必事先宣告變數,這一點對剛學程式語言的人甚為方便,
不過為了以後程式除錯和維護方便,我建議你還是養成事先宣告變數的習慣比較好。
String Operator | Purpose |
x | Returns a string consisting of the string on the left of the operand, repeated the number of times of the right operand. |
. | Concatenates the two strings on both sides of the operator. |
eq | Returns True if the two operands are equivalent, False otherwise. |
ne | Returns True if the two operands are not equal, False otherwise. |
le | Returns True if the operand on the left is stringwise less than the operand on the right of the operator. Returns False otherwise. |
lt | Returns True if the operand on the left is stringwise less than or equal to the operand on the right of the operator. Returns False otherwise. |
ge | Returns True if the operand on the left is stringwise greater than or equal to the operand on the right of the operator. Returns False otherwise. |
gt | Returns True if the operand on the left is stringwise greater than the operand on the right of the operator. Returns False otherwise. |
cmp | Returns -1, 0, or 1 if the left operand is stringwise less than, equal to, or greater than the right operand. |
, | Evaluates the left operand, the evaluates the right operand. It returns the result of the right operand. |
++ | Increments the string by one alphabetic value. |
◎數值運算子
Value Operator | Purpose |
+ | Computes the additive value of the two operands. |
- | Computes the difference between the two operands. |
* | Computes the multiplication of the two operands. |
/ | Computes the division between the two operands. |
% | Computes the modulus(remainder) of the two operands. |
= = | Returns Ture if the two operands are equivalent, False otherwise. |
!= | Returns Ture if the two operands are not equal, False otherwise. |
<= | Returns Ture if the operand on the left is numerically less than or equal to the operand on the right of the operator. Returns False otherwise. |
=> | Returns Ture if the operand on the left is numerically greater than or equal to the operand on the right of the operator. Returns False otherwise. |
< | Returns Ture if the operand on the left is numerically less than the operand on the right of the operator. Returns False otherwise. |
> | Returns Ture if the operand on the left is numerically greater than the operand on the right of the operator. Returns False otherwise. |
< = > | Returns -1 if the left operand is less than the right, +1 if is it greater than, and 0(False) otherwise. |
&& | Performs a logical AND operation. If the left operand is True m then the right operator is not evaluated. |
|| | Performs a logical OR operation. If the left operand is True m then the right operator is not evaluated. |
& | Returns the valueof the two operators bitwise ANDed. |
| | Returns the valueof the two operators bitwise ORed. |
^ | Returns the valueof the two operators bitwise XORed. |
++ | Increment operator. Increments the variable's value by 1. |
-- | Decrement operator. Decrements the variable's value by 1. |
** | Computes the power of the left-hand value to the power of the rihght-hand value. |
+= | Adds the value of the right-hand operand to the value of the left-hand operand. |
-+ | Subtracts the value of the right-hand operand to the value of the left-hand operand. |
*= | Mlutiplies the value of the left-hand operand to the value of the right-hand operand. |
>> | Shifts the left operand right by the number of bits that is specified by the right operand. |
<< | Shifts the left operand left by the number of bits that is specified by the right operand. |
~ | Performs a 1s complement of the operator. This is a unary operator. |
純量陣列,陣列內的每一個元素都是Scalar variable。宣告及使用方式如下:
# 純量陣列以 @ 開頭。
my @array;
my @array=qw(a b c d);
# qw 函數會將其後的每個元素用逗點隔開,效果就像下面這行。
my @array=("a","b","c","d");
# 當然你也可以一個個元素宣告,下面就是存取每一個元素的方法。
# 因為陣列中的每一個元素都是純量變數,所以要以 $ 開頭,
# 剛開始容易搞混,請注意。
$array[0]="a"; $array[1]="b"; $array[2]="c"; $array[3]="d";
# 使用for loop印出陣列內每個元素的值。
for($i=0; $i<=$#array; $i++) {
print "$array[$i]/n";
}
看到$#array這個奇怪的東東沒? 這是Perl的一個特殊用法,代表這個陣列最後一個元素的註標。
由於Perl不必事先宣告變數,也不必預先宣告陣列的大小,甚至可以隨時增加新元素,那我們怎麼知道這個陣列到底有多大呢?
透過這個特殊變數我們可以得知這個這個陣列最後一個元素的註標,自然而然也就知道這個陣列究竟有多大了。
另外Perl只定義了一維陣列的語法,二維以上只能用指標間接來達成。
(c) Hash Array(Associative Array):
Perl有上述三個函數可對相關陣列做運算:keys函數可取出相關變數的索引值,組成一純量陣列,注意這些由keys函數取出的索引值沒有次序性;values函數可取出相關變數的元素值;each函數則會取出(索引、元素)對。使用者可視情況而用。
Perl 5新增了參考指標的資料型態,使Perl和C一樣可借由指標建立一些複雜的資料結構。 普通程式是用不到指標這玩意的,下面也只是簡單介紹一下,看不懂的人可不必深究。
$scalarRef=/$scalarVar;
$arrayRef=/@arrayVar;
$hashRef=/%hashVar;
$funcRef=/&funcName;
⊙如何使用指標?
print $$scalarRef;
print "@$arrayRef";
print $hashRef->{$key};
&$funcRef;
⊙Anonymous Array References:(二維陣列)
$arrayRef=[[1,2,3,4],a,b,[x,y,z],c];
print "$arrayRef->[0][0]/t$arrayRef->[2]/t$arrayRef->[3][2]/n";
⊙Anonymous Hash References:
$hashRef={a=>aa,b=>bb,c=>cc};
print "$hashRef->{a}/t$hashRef->{b}/t$hashRef->{c}/n";
(2) 控制敘述(Control Statements)
(b) Loop Control Statements:
Perl的迴圈控制敘述也和C語言很像,當然,照例Perl也另外多了些實用的語法:
(b) 呼叫副程式: &NAME(para1, para2,...)
(c) 參數傳遞: @_ Perl和C一樣是採用Call by value的方式,不過因為Perl不用事先宣告變數,所以建立副程式的時候也不用宣告要傳遞什麼參數。 當主程式在傳遞參數給副程式時,Perl會把括號括起來的參數按順序放在一個特殊的全域變數 @_ 陣列中,然後副程式就可以隨意使用陣列 @_ 裡的參數,例如 $_[0] 是第一個參數, $_[1] 是第二個,或是用
my ($a1,$a2,$a3,...) = @_;
來取出各個參數,當然 my @arg=@_;
或 my %arg=@_;
也是可以的。
由於Perl的語法非常活潑,使得程式在維護時特別棘手,因此寫註解成為一項很重要的工作。
我建議你最好在每個副程式前面加上對這段副程式的描述,特別是需要傳遞的參數要註明清楚。
(d) Variable Localization:my or local
通常我們在程式中定義的變數都是全域變數,所以在副程式中若要把變數區域化則要加上 my 或 local 關鍵字,例如:
my $x=3;
,若副程式所用的變數名不小心和主程相同,Perl會以目前正在執行的副程式裡的變數為優先。
(a) Syntax:
open(FILEHANDLE,"Expression");close(FILEHANDLE); 這裡的Expression是一個敘述加上檔案名稱,若Expression只有檔案名稱沒有加上敘述,則預設是唯讀。Expressions敘述如下:
Expression | Effect |
open(FH, "<filename") | Opens filename for reading. |
open(FH, "+<filename") | Opens filename for both reading and writing. |
open(FH, ">filename") | Opens filename for writing. |
open(FH, "+>filename") | Opens filename for both reading and writing. |
open(FH, ">>filename") | Appends to filename. |
open(FH, "command|") | Runs the command and pipes its output to the filehandle. |
open(FH, "command|") | Pipes the output along the filehandle to the command. |
open(FH, "-") | Opens STDIN. |
open(FH, ">-") | Opens STDOUT. |
open(FH, "<&=N") | Where N is a number, this performs the equivalent of C's fdopen for reading. |
open(FH, ">&=N") | Where N is a number, this performs the equivalent of C's fdopen for writing. |
例:
# 開啟$filename這個檔案,若開啟失敗則印出die後面的訊息,並結束程式。
open(FILE, $filename) || die "Can't open file $filename : $!/n";
# 下面是一個十分精簡的寫法,和 while($_=<FILE>){print "$_";} 是等效的。
print while(<FILE>);
# 檔案開啟後要記得隨手關閉,這才是寫程式的好習慣。
close(FILE);
# $!和$_都是Perl的特殊變數,下面會介紹的。
(b) Input: Perl沒有特別用來輸入的函數,因為Perl在執行程式時,會自動開啟標準輸入裝置,其filehandle定為STDIN,所以在Perl中要輸入資料的方法就是使用<STDIN>: (c) Output: print "variables or 字串"; Perl也有printf()函數,語法和C語言一模一樣,我就不多做介紹了。Perl另外有個print函數,比printf()更方便、更好用,包你愛不釋手。 Output不外乎是輸出到螢幕或檔案,用例子來說明比較容易了解。
/t tab
/n newline
/r return
/f form feed
/b backspace
/a alarm(bell)
/e escape
/033 octalchar
/x1b hex char
/c[ control char
/l lowercase next char
/u uppercase next char
/L lowercase till /E
/U uppercase till /E
/E end case modification
/Q quoteregexp metacharacters till /E
$x="ls -l";
print "$x"; # Output ls -l
print "/$x"; # Output $x
print '$x'; # Output $x
print `$x`; # Output files in this directory
(5) Regular Expressions
Syntax: $string =~ /regular expression/expression modifier
(a) Modifiers:修飾選項可有可無,它是用來對整個敘述作修正的。g | Match globally, i.e. find all occurrences. |
i | Makes the search case-insensitive. |
m | If the string has new-line characters embedded within it, the metacharacters ^ and $ will not work correctly. This modifier tells Perl to treat this line as a multiple line. |
o | Only compile pattern once. |
s | The character . matches any character except a new line. This modifier treats this line as a single line, which allows . to match a new-line character. |
x | Allows white space in the expression. |
/ | Tells Perl to accept the following characters as a regular character; this removes special meanings from any metacharacter. |
^ | Matches the beginning of the string, unless /m is used. |
. | Matches any character except a new line character, unless /s is used. |
$ | Matches the end of the string, unless /m is used. |
| | Expresses alternation. This means the expressions will search for multiple patterns in the same string. |
( ) | Groups expressions to assist in alternation and back referencing. |
[ ] | Looks for a set of characters. |
* | Matchs 0 or more times. |
+ | Matchs 1 or more times. |
? | Matchs 0 or 1 times. |
{n} | Matches exactly n times. |
{n,} | Matches at least n times. |
{n,m} | Matches at least n times but no more than m times. |
/r | Carriage return(CR), ASCII 13(十進位) |
/n | New line, UNIX中代表ASCII 10(十進位), DOS(Windows)系統中則是ASCII 13 + ASCII 10(十進位). |
/t | Tab, ASCII 9(十進位) |
/w | Matches an alphanumeric character. Alphanumeric also includes _. 即 [A-Za-z0-9_]. |
/W | Matches a nonalphanumeric character. 即 [^A-Za-z0-9_]. |
/s | Matches a white space character. This includes space, tab, FormFeed and CR/LF. 即 [/ /t/f/r/n]. |
/S | Matches a non-whote space character. 即 [^/ /t/f/r/n]. |
/d | Matches a digit. 即 [0-9]. |
/D | Matches a nondigit character. 即 [^0-9]. |
/b | Matches a word boundary. |
/B | Matches a nonword boundary. |
/033 | octal char |
/x1B | hex char |
/^abc/
找到開頭是abc的字串
/abc$/
找到結尾是abc的字串
/a|b/
找到有a或b的字串,也可以用來找整個字(word)
/ab{2,4}c/
找到a後面跟著2-4個b,再跟著c的字串,若只有/ab{2,}c/則會找二個以上的b
/ab*c/
找到a後面跟著0個或多個b,再跟著c的字串,如同/ab{0,}c/
/ab+c/
找到a後面跟著一個以上的b,再跟著c的字串,如同/ab{1,}c/
/a.c/
.可以代表任何字元,除了new line字元(/n)外。
/[abc]/
找到含有這三個字元中任何一個的字串
//d/
找到含有數字的字串,如同/[0-9]/
//w/
找到含有字母的字串,如同/[a-zA-Z0-9_]/
//s/
找到含有white space的字串,如同/[ /t/r/n/f]/
/[^abc]/
找到沒有abc任一字元的字串
//*/
找到含有字元*的字串,在反斜線"/"後面的字元Perl會把它當作普通字元看待。若你不確定這個符號是否為特殊字元,乾脆全加上/以策安全。
/abc/i
忽略abc的大小寫
/(/d+)/.(/d+)/.(/d+)/.(/d+)/
找到類似IP的字串,並將IP的四個數字分別存在$1,$2,$3,$4四個特殊變數中,以便在其後加以利用。例:
if ($x =~ /(/d+/./d+)/./d+/./d+/) {
print "海洋大學" if ($1 eq "140.121");
}
m//gimosx
m命令可以讓你自訂pattern的分隔符號,而gimosx則是它的修飾選項,請參看(a)Modifiers。例如:
這個Regular Expression相當複雜,主要目的是分析指定的URL,然後取得host名稱、port號碼及對應的檔案。我一項項慢慢解釋:
$url=~m||
m後面跟著的就是分隔符號,| |裡面的就是pattern。
([^/:]+)
match一個字串,裡面沒有/和:字元。找到的字串存在$1中。
:{0,1}(/d*)
match 0或1個:,後面跟著一串數字或nothing。找到的字串存在$2中,若找不到,$2就是空的。
(/S*)$
match一串非空白字元,並以找到的字串為結尾。找到的字串存在$3中。
()=()
($host, $port, $file)=($1, $2, $3)
即$host="my.machine.tw"
$port=8080
$file="/cgi-bin/test.pl"
s/PATTERN/REPLACEMENT/egimox
沒錯,這就是取代的命令。它會尋找符合PATTERN的字串,並取代成REPLACEMENT字串。它的修飾選項多了e選項,其他的和上面都一樣,我將它列表如下:
e | Evaluate the right side as an expression. |
g | Replace globally, i.e. all occurrences. |
i | Do case-insensitive pattern matching. |
m | Treat string as multiple lines. |
o | Only compile pattern once. |
s | Treat string as single line. |
x | Use extended regular expressions. |
例:$x =~ s//s+//g
把所有的white space全部去除掉
$x =~ s/([^ ]*):*([^ ]*)/$2:$1/
把用":"分開的兩個欄位互相對調
$path =~ s|/usr/bin|/usr/local/bin|
它也可以讓你自訂分隔符號哦
tr/SEARCHLIST/REPLACEMENTLIST/cds
c | Complement the SEARCHLIST. |
d | Delete found but unreplaced characters. |
s | Squash duplicate replaced characters. |
例:$x =~ tr/this/that/
把"this"替換成"that"
$x =~ tr/a-z/A-Z/
把小寫字母全部替換成大寫字母
$count = $x =~ tr/*/*/
計算$x中有幾個"*"
$_ | The default input and pattern-searching space. |
$digit | Contains the subpattern from a successful parentheses pattern match. |
$. | The current input line number of last filehandle read. |
$! | Contains the current value of errno. |
$0 | The name of the file of the Perl script. |
@ARGV | The command line arguments issued when the script was started. |
@_ | The parameter array for subroutines. |
%ENV | This associative array contains your current environment. |
首先你可以到各大BBS站的WWW板或program板的精華區找找,不過資料不會很多,而且有點雜亂。 再不然你可以到蕃薯藤輸入perl或cgi關鍵字找找,有不少人的homepage上有教人如何用Perl寫CGI程式,還有一堆別人已經寫好的CGI程式可以抓來用用。 說到這裡順便打一下廣告,在http://ind.ntou.edu.tw/documents下有Perl的說明文件,做得相當不錯,不過全是英文的就是了,而我這份講義打好後也會放在IND的homepage上,大家可以抓回去參考參考。
第三種資源就是Perl本身的man pages,你在IND帳號下鍵入 man perl 就可以查閱了,這份文件做得不錯,還根據Perl的各個部分寫了man pages,如Perl syntax, builtin function, regular expression, data structure等, 大家可以用man指令一一查詢,有時候在寫程式時一時忘了某個函數怎麼用,這倒是個方便又快速的查詢方法。我會把這些man pages轉成html格式,放在WWW上讓大家參考。
相关推荐
perl基本语法 讲述数据类型 控制叙述 副程式 I/O和档案处理等
perl基本语法,适合初学perl的人员。
包含了全部的基本Perl语法,对初学Perl者很有帮助
PERL_基本语法,针对PERL刚刚入门初学者,可以加深对PERL的印象
perl基本语法 一字一字的自学敲上去的 心血啊 所以分比较高 勿怪
Perl 基本语法 by Jian Lee
是比较好的perl的入门教材; 里面有详细的Perl的基本语法的描述,同时对正则表达式也有较好的介绍.
vscode-perls语法 Visual Studio Code的基本Perl语法荧光笔。
PHP基本语法一 大纲 一、掌握PHP基本语法 二、掌握PHP变量、常量、数据类型 第一节 PHP语法的概述 PHP语法主要借鉴于C/C++,也部分参考了Java和Perl。 类似C语言,书写PHP代码的时候,每句完成代码后都要以分号“;...
基础篇,主要介绍 Perl 的基本语法、数组、哈希、输入输出、函数等。 高级篇,介绍 Perl 的正则表达式、模块 module、面向对象 OOP、 多进程等。 实战篇,介绍 Perl 在芯片设计、验证中的应用。 另外,修正了一些...
Perl 学习手札,这本书介绍了perl的基本语法及perl的一些用法,想了解perl的就看一看
PHP正则表达式基本语法和使用方法 一、实验环境 1、环境搭建:Windows 8+Apache 2.4.18+MySQL 5.7.11+PHP 7.1.0 。 2、文本编辑器:Sublime Text3。 二、主要技术 正则表达式(regular expression)是一种表示方式,...
perl语言速成,包括perl基本的语法结构和实例
非常实用的Perl编程教程,从基本的Perl语法讲起到Perl的高级应用,教程中涵盖了诸多知识点,全面到位,还包含了很多的demo,是学习Perl的必备资料.
perl参考大全第二部分, 包括从基本语法到数据库应用等各方面
该文档主要介绍了Perl语言的基本语法及正则表达式的含义
本书是perl的经典入门书籍,介绍了perl中最基本的概念和语法,是perl入门的好书,我向所有想了解或学习perl语言的朋友推荐本书。书中穿插有perl语法形成的历史和原因,使你能充分感受到perl语言的文化,这也是perl...
包含Perl语言的语法讲解,每章都配套有示例代码,包括了perl环境搭建教程,基本涵盖了perl语言的所有语法。
Perl 不会强迫你学习新的语法和语意,Perl 改从许多其它你已经熟悉的语言里(比如 C, awk, BASIC 和 Python, 英文,希腊语等)借来语法。实际上,任何程序员都可以从书写良好的 Perl 代码段中读懂它的含义。 ...