發新話題

Perl的基本語法 - I/O和檔案處理

Perl的基本語法 - I/O和檔案處理

I/O和檔案處理 [size=+1](a) Syntax: open(FILEHANDLE,"Expression");
close(FILEHANDLE);這裡的Expression是一個敘述加上檔案名稱,若Expression只有檔案名稱沒有加上敘述,則預設是唯讀。Expressions敘述如下:

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

[size=+1]例:
# 開啟$filename這個檔案,若開啟失敗則印出die後面的訊息,並結束程式。
open(FILE, $filename) || die "Can't open file $filename : $!\n";
# 下面是一個十分精簡的寫法,和 while($_=<FILE>){print "$_";} 是等效的。
print while(<FILE>);
# 檔案開啟後要記得隨手關閉,這才是寫程式的好習慣。
close(FILE);
# $!和$_都是Perl的特殊變數,下面會介紹的。


[size=+1](b) Input:Perl沒有特別用來輸入的函數,因為Perl在執行程式時,會自動開啟標準輸入裝置,其filehandle定為STDIN,所以在Perl中要輸入資料的方法就是使用<STDIN>: [size=+1]# Perl不會自動去掉結尾的CR/LF,跟C語言不同,所以要用chomp函數幫你去掉它。
# 大家常常會忘記這個動作,導致結果跟你想的不一樣,要特別注意一下。
$input=<STDIN>; chomp $input;
# 下面是較簡潔的寫法。
chomp($input=<STDIN>);


[size=+1](c) Output: print "variables or 字串";Perl也有printf()函數,語法和C語言一模一樣,我就不多做介紹了。Perl另外有個print函數,比printf()更方便、更好用,包你愛不釋手。 Output不外乎是輸出到螢幕或檔案,用例子來說明比較容易瞭解。 [size=+1]# 不用再指定變數的data type,這樣不是比printf()方便多了嗎?
print "Scalar value is $x\n";
# . 是字串加法的運算子,上下這兩行是等效的。
print "Scalar value is " . $x . "\n";

# 輸出到檔案的方法。
print FILE "print $x to a file.";

# 下面是print的特殊用法,學自shell script的用法:
print<<XXX;
這招叫做 here document,XXX可以是你取的任何識別字,在識別字之間的字都會按照你所寫的樣子輸出,就像<pre>標籤一樣。而當一行的開頭是XXX你取的這個識別字時,才會停止輸出。XXX
Perl 也有和 C 一樣以 "\" 開頭的特殊字元:       \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另外需要說明的是 Perl 融合了 unix shell script 的使用慣例,以雙引號("")括起來的字串會先經過展開,但反斜線(\)後面的字元則不展開,當作一般字元看待。而以單引號('')括起來的字串完全不會展開,以反單引號(``)括起來的字串會把它當作命令列指令一樣執行,等於system()一樣。初學者常常會搞混,但習慣之後就會覺得不這樣分清楚反而不行哩。舉個例吧: [size=+1]$x="ls -l";print "$x";             # Output ls -lprint "\$x";            # Output $xprint '$x';             # Output $xprint `$x`;             # Output files in this directory

TOP

發新話題

本站所有圖文均屬網友發表,僅代表作者的觀點與本站無關,如有侵權請通知版主會盡快刪除。