简体   繁体   English

如何在同一Perl脚本中读取整个文件和逐行文件

[英]How to read the whole file and line by line file in the same Perl script

Whenever I want Perl to read the whole file I put undef $/ before reading the file. 每当我想让Perl读取整个文件时,在读取文件之前我都会先输入undef $/ I tried to find more information about the variable $/ but without success. 我试图找到有关变量$/更多信息,但没有成功。

What I need to do is to write a script in Perl that first reads the whole file to a variable and then read another file line by line. 我需要做的是在Perl中编写一个脚本,该脚本首先将整个文件读取为变量,然后逐行读取另一个文件。 How could this be done? 怎么办呢?

You can try opening and reading the first file in a local scope, and then limit the setting of $/ to that scope. 您可以尝试在本地范围内打开和读取第一个文件,然后将$/的设置限制为该范围。

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

# continue with $/ still set

Link: 链接:

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

Either that, or save the value of $/ to another variable before setting it to undef , and then reset it after reading the first file. 或者,或者将$/的值保存到另一个变量,然后再将其设置为undef ,然后在读取第一个文件后将其重置。

If you don't want to use $/ , look into File::Slurp . 如果您不想使用$/ ,请查看File::Slurp There is a section on using it in the link I provided. 我提供的链接中有关于使用它的部分。

Here's another way to do it without directly using $/. 这是另一种无需直接使用$ /的方法。

You can use File::Slurp's read_file to read the first file and store its data in memory. 您可以使用File :: Slurp的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);

And, the simplest reading method to read the second file line by line. 并且, 最简单的读取方法是逐行读取第二个文件。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM