2014-03-19 19 views

回答

1

您可以使用替代s///運算符和eval評估/ee修飾符來創建一些非常簡單的操作。

像這樣的事情

use strict; 
use warnings; 

my $template = <<'END'; 
<file> 
    <state>$state</state> 
    <timestamp>$time</timestamp> 
    <location>$location</location> 
</file> 
END 

my $state = 'Oregon'; 
my $time  = '10:04'; 
my $location = 'Salem'; 

(my $output = $template) =~ s{(\$\w+)}{ $1 }eeg; 

print $output; 

輸出

<file> 
    <state>Oregon</state> 
    <timestamp>10:04</timestamp> 
    <location>Salem</location> 
</file> 
+0

哇!那簡單而美麗。現在我會看到更多關於'/ ee'的信息,看看它有多強大。 – 719016

+1

@ 200508519211022689616937:這是你*必須非常小心的事情,因爲在字符串上調用'eval'可能會造成嚴重的損害。在這種情況下是安全的,因爲被評估的字符串始終是標量變量的名稱,所有'eval'都可以返回該變量的內容。但是沒有什麼能夠阻止一個字符串包含一個完整的Perl程序來刪除文件,並且通常會對系統造成嚴重破壞。如果您的字符串來自程序之外,並且可能由惡意用戶提供,請加倍小心。 – Borodin

1

明顯的推論鮑羅廷的建議解決方法就是使用哈希來初始化數據。鑑於他通過將正則表達式的LHS限制爲單詞字符來保護您,這在功能上是相同的。但使用散列可能是更好的做法,因爲只有那些你想要導入模板的變量。

此外,您會使用這種方法得到稍微好一點的錯誤信息:

use strict; 
use warnings; 

my $template = <<'END'; 
<file> 
    <state>$state</state> 
    <timestamp>$time</timestamp> 
    <location>$location</location> 
</file> 
END 

my %data = (
    state => 'Oregon', 
    time  => '10:04', 
    location => 'Salem', 
); 

(my $output = $template) =~ s{\$(\w+)}{ 
    $data{$1} // die "Variable '$1' from template not initialized" 
}eg; 

print $output;