2016-04-27 32 views
3
open my $directory, '<', abc.txt 

chomp(my @values = <$directory>); 

有具有以下內容名爲abc.txt一個文件:如何爲文件中的每一行執行命令?

abcde 
abc 
bckl 
drfg 
efgt 
eghui 
webnmferg 

利用上述線,我送文件abc.txt的內容到一個數組

意圖是創建一個循環來運行在文件的所有行上的命令abc.txt

有關創建循環的任何建議嗎?

+3

爲什麼變量保存文件句柄叫'$ directory'?這在IT環境中非常模糊。爲您的變量使用有意義的名稱! – simbabque

回答

3
open my $directory_fh, '<', abc.txt or die "Error $! opening abc.txt"; 
while (<$directory_fh>) { 
    chomp; # Remove final \n if any 
    print $_; # Do whatevery you want here 
} 
close $directory_fh; 

我寧願後綴的所有文件句柄與_fh使他們更加明顯。

while (<fh>)循環通過文件的所有行。

如果文件可能具有Windows/MS-DOS格式,則可能需要/想要刪除最後的\r

+3

實際上'chomp'去除了'$ /'中的任何內容。 – simbabque

1

創建一個循環來對文件的所有行運行命令的abc.txt

foreach my $line (@lines){ 
     #assugming $cmd contains the command you want to execute 
     my $output = `$cmd $line`; 
     print "Executed $cmd on $line, output: $output\n"; 
} 

編輯:按照塞巴斯蒂安的反饋

my $i = 0; 
while ($i <= $#lines){ 
     my $output = `$cmd $lines[$i]`; 
     print "Executed $cmd on $lines[$i], output: $output\n"; 
} 

,或者如果您沒有問題摧毀陣列然後:

while (@lines){ 
     my $line = shift @lines; 
     my $output = `$cmd $line`; 
     print "Executed $cmd on $line, output: $output\n"; 
} 

如果您想要兩次未引用陣列的安全代碼,則可以在列表分配中使用拼接。

while (my ($line) = splice(@array, 0, 1)) { 
     my $output = `$cmd $line`; 
     print "Executed $cmd on $line, output: $output\n"; 
} 
+0

'for'解決方案將整個文件內容加載到內存中,可能會變得非常龐大,'while'只加載一行(以Perl的緩衝區大小爲單位)。 – Sebastian

+0

正確。我已根據您的輸入更新了答案。謝謝。 –

相關問題