在perl中打开多行文本文件

open multiline text file in perl

我有以下文本文件

Hello my
name is
Jeff

我想用 perl 打开它。但是,当使用此代码时

use strict;
use warnings;
open(my $fh, "<", "input.txt") or die "cannot open input text!";
my $text= <$fh>;
print $text;

输出文本只有Hello my。我怎样才能让它打印我所有的输入文本行而不仅仅是第一行?

In scalar context, evaluating a filehandle in angle brackets yields the next line from that file

因此您可以使用 while 循环读取行(首选方法)

while (<$fh>) #output will store into default variable $_
{
    print ; 

}

或者您可以使用数组,但您试图将文件的所有内容存储在变量中

my @array = <$fh>;

以及读取标量变量中所有文件的slurp模式

my $multiline = do { local $/; <$fh>; } #$/ input record seprator

如果您阅读 section on I/O operators in perldoc perlop,您将看到以下内容:

In scalar context, evaluating a filehandle in angle brackets yields the next line from that file

再往下一点:

If a <FILEHANDLE> is used in a context that is looking for a list, a list comprising all input lines is returned, one line per list element.

如果您将 <FILEHANDLE> 分配给标量变量,您将从文件中获取下一行(实际上是记录)。这就是你正在做的:

my $text = <$fh>;

如果将 <FILEHANDLE> 分配给数组,您将从文件中获取所有剩余数据,每一行(实际上是记录)在数组的单独元素中。

my @text = <$fh>;

如果您想将文件中的所有数据转换为标量,可以采用几种方法。天真的方法是读取列表上下文中的数据,然后使用空字符串连接它:

my $text = join '', <$fh>;

您可以使用 $/ 来改变 Perl 对 "record" 的想法(通常在 do 块中完成):

my $text = do { local $/; <$fh> };

我喜欢the slurp method from Path::Tiny

use Path::Tiny;

my $text = path($filename)->slurp;