跳轉到內容

Perl 程式設計/高階輸出

來自華夏公益教科書,開放書籍,開放世界
上一頁: 使用者輸入輸出 索引 下一頁: 檔案控制代碼


高階輸出概述

[編輯 | 編輯原始碼]

在許多情況下,特別是對於 Web 程式設計,你會發現你想要在你的文字中放入一些東西,比如反斜槓或引號,這些東西在傳統的 print 語句中是不允許的。像這樣的語句

print "I said "I like mangos and bananas". ";

將無法工作,因為直譯器會認為引號標記字串的結尾。就像 Perl 中的所有東西一樣,這個問題有很多解決方案。

使用其他引號

[編輯 | 編輯原始碼]

解決這個問題最快的辦法是使用單引號來包圍字串,允許在中間使用雙引號。

# I said "I like mangos and bananas".
print 'I said "I like mangos and bananas".';

這顯然不是最好的解決方案,因為可以想象你正在嘗試列印包含兩種引號的字串

# I said "They're the most delicious fruits".
print 'I said "They're the most delicious fruits".';

跳脫字元

[編輯 | 編輯原始碼]

對於像上面那樣只引用少量文字的情況,一個常見的解決方案是 *轉義* 字串中的任何引號。在任何引號之前加上一個反斜槓,它們就會被視為文字字元。

 print 'I said "They\'re the most delicious fruits".';
 print "I said \"They\'re the most delicious fruits\".";

使用單引號,需要轉義的字元是\'.

使用雙引號,需要轉義的字元是變數 sigils,(即$@%*)以及\"

使用\來轉義保留字元當然意味著你還需要跳脫字元串中要使用的任何反斜槓。要使用 perl 列印第二行,你需要寫

 print " print \"I said \\\"They\\\'re the most delicious fruits\\\".\";"

幸運的是,Perl 為我們提供了另一種引用字串的方法,可以避免這個問題。

自定義引號

[編輯 | 編輯原始碼]

Perl 提供了運算子qqq它允許你決定哪些字元用於引用字串。大多數標點符號都可以使用。以下是一些例子

 print qq{ I said "They're the most delicious fruits!". };
 print q! I said "They're the most delicious fruits\!". !;

我發現的唯一不能用於這些引號的符號是$ ` /

塊輸出

[編輯 | 編輯原始碼]

正如所見,雖然自定義引號選項適用於短字串,但如果要輸出很多包含很多標點符號的文字,它可能會遇到問題。對於這種情況,可以使用稱為塊引用的技術。

  print <<OUTPUT
    I said "They're the most delicious fruits!".
  OUTPUT
  ;

在上面的例子中,任何字元的字串都可以用來代替 OUTPUT。使用這種技術,任何東西都可以輸出,無論它包含什麼字元。這種方法唯一的注意事項是,關閉的 OUTPUT 必須是行上的第一個字元,前面不能有任何空格。

  print <<EverythingBetween
    ...
    ...
  EverythingBetween

變數輸出

[編輯 | 編輯原始碼]

使用這些方法中的某些方法,可以輸出字串中的變數

my $one = 'mangoes';

print "I like $one.";    # I like mangoes.
print 'I like $one.';    # I like $one.
print qq@ I love $one.@; # I love mangoes.
print q#I love $one.#;   # I love $one.

print <<OUT
  I love $one
OUT
;                        #  I love mangoes

print <<'OUT'
  I love $one
OUT
;                        #  I love $one

如果變數後的字元既不是字母,也不是數字,也不是下劃線,Perl 會找出你的變數在哪裡結束。如果不是這種情況,請將你的變數放在花括號中

my $one = 'lemon';

print "A $one is too sour; ";	# A lemon is too sour;
print "${one}ade is better.\n";	# lemonade is better.

print <<OUT
 I love ${one}s in $one souffle.
OUT
;                        #  I love lemons in lemon souffle.

注意事項

[編輯 | 編輯原始碼]

單引號' q{和雙引號" qq <<A運算子的行為有所不同。當使用雙引號時,你可以包含變數並轉義任何字元,而當你使用單引號時,你只能轉義單引號,並且不能包含變數。


上一頁: 使用者輸入輸出 索引 下一頁: 檔案控制代碼
華夏公益教科書