2014-07-23 35 views
0

我有具有在數據部分硬編碼輸入數據這Perl代碼:讀取在__DATA__格式的輸入文件中的Perl

__DATA__ 
M19, Q, P, 
M31, M19, Pl, 
M420, M31, E, 
M421, M31, E, 
M33, M31, E, 
M438, M33, Pl, 
M445, M33, E, 
M437, M33, E, 

該硬編碼數據是由下面的代碼處理:

split /,\s*/ for <DATA>; 

我已將數據複製到與代碼相同的目錄中的單獨input.txt文件中。但我希望文件被讀爲用戶輸入。但我不知道如何以與__DATA__相同的方式讀取輸入文件。下面是我使用的是什麼,這是不工作:

print ("Enter the file") 

用戶輸入input.txt

chomp(my $file=<STDIN>); 

回答

1

嘗試使用此方法得到用戶輸入的文件名:

print "enter the file name\n"; 
    chomp(my $file=<STDIN>); 
    open(DATA,$file) or die "failed to open this file!!"; #this will open the file in the file-handle DATA if the file exists in the same directory else it will die 

現在你可以像拆分功能一樣拆分內容:

split /,\s*/ for <DATA>; 
0

您可以使用Perl函數open

您可以使用

open(FH, $file); 

打開該文件,然後用

<FH> 

就像你在拆分

+0

做處理可能你爲這個迴應添加更多細節?例如,如何使用'open()'的例子? – Kenster

+0

編輯該問題並解釋如何使用它。 – ProfGhost