【问题标题】:How to read the whole file and line by line file in the same Perl script如何在同一个 Perl 脚本中逐行读取整个文件
【发布时间】:2015-10-04 20:10:45
【问题描述】:

每当我想让 Perl 读取整个文件时,我都会在读取文件之前输入undef $/。我试图找到有关变量$/ 的更多信息,但没有成功。

我需要做的是在 Perl 中编写一个脚本,首先将整个文件读取到一个变量中,然后逐行读取另一个文件。这怎么可能?

【问题讨论】:

标签: perl


【解决方案1】:

您可以尝试在本地范围内打开和读取第一个文件,然后将$/ 的设置限制在该范围内。

my $firstfile;
{
    open my $fh, '<', $file or die;
    local $/ = undef;
    $firstfile = <$fh>;
    close $fh;
}

# continue with $/ still set

链接:

http://perlmaven.com/slurp(部分:本地化更改)

要么这样,要么将$/ 的值保存到另一个变量中,然后再将其设置为undef,然后在读取第一个文件后将其重置。

如果您不想使用$/,请查看File::Slurp。在我提供的链接中有一个关于使用它的部分。

【讨论】:

    【解决方案2】:

    这是另一种不直接使用 $/ 的方法。

    您可以使用File::Slurp's read_file 读取第一个文件并将其数据存储在内存中。

    my $text = read_file('filename');
    my $bin = read_file('filename' { binmode => ':raw' });
    my @lines = read_file('filename');
    my $lines = read_file('filename', array_ref => 1);
    

    并且,simplest reading method 逐行读取第二个文件。

    open(my $fh, '<', 'input.txt');
    while (my $line = <$fh>) {
        ...
    }
    close $fh;
    

    【讨论】:

      猜你喜欢
      • 2012-10-13
      • 1970-01-01
      • 2017-12-20
      • 2012-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多