2013-09-23 110 views
0

我知道文件名可以在perl腳本中變量。是否同樣適用於cgi-perl腳本。因爲當我在open語句中使用變量時,出現錯誤No這樣的文件或目錄。但是,當我直接提到文件打開閱讀的路徑。這些變量是從窗體傳遞的。值正確傳遞它們不是空的(通過打印可變參數進行檢查)。可以目錄名稱和文件名是cgi perl腳本中的變量

實施例:

$dir=abc; 
$file=file1; 

open (FILE, '/var/www/cgi-bin/$dir/$file') 
    or print "file cannot be opened $!\n"; 

錯誤:

file cannot be opened no such file or directory

回答

2

使用雙引號內插變量:

open (FILE, "/var/www/cgi-bin/$dir/$file") 
# here __^    and here __^ 
    or print "file cannot be opened $!\n"; 

還有,經常

use strict; 
use warnings; 

通過使用單引號時,可變因素aren'tt插值,所以你想從字面上打開/var/www/cgi-bin/$dir/$file和它不存在。

+0

這有效。我可以知道爲什麼單個qoutes不起作用嗎? – Nagaraju

+2

@Raju:因爲單引號內的變量不是插值。請參閱http://perldoc.perl.org/perlop.html#Quote-and-Quote-like-Operators – Toto

1

你已經(並接受)一個很好的答案。我只是想補充一點,如果在字符串中包含$file的值,則可以使錯誤消息更加有用。

my $file_path = '/var/www/cgi-bin/$dir/$file'; 
open (FILE, $file_path) 
    or print "file [$file_path] cannot be opened: $!\n"; 

然後錯誤會一直「文件[/無功/網絡/ cgi-bin目錄/ $ DIR/$文件]不能打開:沒有這樣的文件或目錄」,這將使它明顯,變量沒有擴大。

更新:我在說廢話。新版本更好。

+0

你確定你會在提到的那個錯誤嗎?在下面的部分[$ file]將被擴展爲雙引號。不是嗎? –

相關問題