簡體   English   中英

如何從Perl中的文本文件讀取輸入?

[英]How can I read input from a text file in Perl?

我想從Perl中的文本文件獲取輸入。 盡管可以從網上獲得許多信息,但是對於如何執行打印文本文件的每一行這一簡單任務仍然感到非常困惑。 那怎么辦呢? 我是Perl的新手,所以很困惑。

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

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

或者,等效地,

#!/usr/bin/perl -p

在命令行上:

perl -pe0 textfile.txt

您應該按照一本不錯的書開始有條不紊地學習該語言,而不是通過在網絡上隨意搜索。

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

請參閱perldoc perltocperldoc.perl.org

例如,打開的文件包含在perlopentut中

首先,打開文件:

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

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

while (<$fh>) {
    # line contents's automatically stored in the $_ variable
}
close $fh or die $!;
# 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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM