2010-08-31 66 views
-1

我想從Perl中的文本文件中獲取輸入。儘管很多信息都可以通過網絡獲得,但對於如何完成打印每一行文本文件這一簡單任務仍然非常困惑。那麼該怎麼做呢?我對Perl很陌生,因此感到困惑。如何從Perl中的文本文件讀取輸入?

+5

你應該得到一本書,並有條不紊地研究語言。請參閱http://learn.perl.org/ – 2010-08-31 14:13:03

+1

@Sinan有一個[有關perl書籍的stackoverflow問題](http://stackoverflow.com/questions/336715/what-are-good-books-for-learning-perl )。 – 2010-08-31 14:19:25

回答

3

首先,打開文件:

open my $fh, '<', "filename" or die $!; 

接下來,使用while循環讀取直到EOF:

while (<$fh>) { 
    # line contents's automatically stored in the $_ variable 
} 
close $fh or die $!; 
4

尤金已經顯示出的正確方法。這裏是一個更短的腳本:

#!/usr/bin/perl 
print while <> 

,或者等價地,

#!/usr/bin/perl -p 
在命令行上

perl -pe0 textfile.txt 

你應該開始學習語言有條不紊,以下像樣的書,而不是通過網絡上的偶然搜索。

您還應該使用Perl附帶的大量文檔。

請參閱perldoc perltocperldoc.perl.org

例如,打開文件在perlopentut中進行了介紹。

+0

這需要'perl -p -e0 textfile.txt'或'perl -p/dev/null textfile.txt'或類似的名稱來保持stdin或textfile.txt不被視爲perl程序運行。 – ysth 2010-08-31 15:13:31

+0

如果你不想在命令行中輸入文件名,我會經常在快速的n髒腳本中進行硬編碼:@ ARGV =「filename.txt」;您也可以在shebang(例如#!/ usr/bin/perl -p)行放置「-p」或「-n」行。 – runrig 2010-08-31 15:26:24

1
# open the file and associate with a filehandle 
open my $file_handle, '<', 'your_filename' 
    or die "Can't open your_filename: $!\n"; 

while (<$file_handle>) { 
    # $_ contains each record from the file in turn 
} 
+0

@ jm666謝謝。我在一個月前修復了一半,然後完全忘了它。現在修復。 – 2017-04-03 12:24:33