如何从Perl中的文本文件中读取输入?

时间:2010-08-31 14:07:42

标签: perl

我想从Perl中的文本文件中获取输入。尽管可以通过网络获得大量信息,但是如何执行打印每行文本文件的简单任务仍然非常令人困惑。那怎么办呢?我是Perl的新手,因此感到困惑。

3 个答案:

答案 0 :(得分:4)

eugene已经展示了正确的方法。这是一个较短的脚本:

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

或等同地

#!/usr/bin/perl -p

在命令行上:

perl -pe0 textfile.txt

你应该开始有条不紊地学习这门语言,遵循一本体面的书,而不是通过网上偶然的搜索。

您还应该使用Perl附带的大量文档。

参见 perldoc perltoc perldoc.perl.org

例如,打开文件包含在perlopentut

答案 1 :(得分:3)

首先,打开文件:

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

接下来,使用while循环读取直到EOF:

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

答案 2 :(得分: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
}
相关问题