读取大文件 (Perl) 后如何使用 SCALAR 逐行读取? [英] How to use SCALAR to read line-by-line after reading in a large file (Perl) ?

查看:96
本文介绍了读取大文件 (Perl) 后如何使用 SCALAR 逐行读取?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下命令将文件读入 SCALAR:

I am reading a file into a SCALAR by using:

open FILE, "<", $filename or error_out("Error opening $filename");
read FILE, my $buffer, -s $filename;    
close FILE;

我不知道如何看待新"$buffer/SCALAR 类型.是字符串吗?数组?如何逐行通过它?

I am not sure how to think of the "new" $buffer/SCALAR type. Is it a string? An array? How to go through it line-by-line?

推荐答案

首先,我建议您使用以下方法阅读文件:

First, I recommend you use the following to read the file:

my $buffer = do {
    open(my $fh, '<', $filename)
        or error_out("Error opening $filename: $!");
    local $/;
    <$fh>
};

注意删除了无用且可能不正确的 -s.请注意使用词法变量作为文件句柄而不是全局变量.请注意错误消息中包含的基础错误消息.

Note the removal of the useless and potentially incorrect -s. Note the use of a lexical variable for the file handle rather than a global one. Note the inclusion of the underlying error message in the error message.

  1. 变量是一个标量.该值是一个字符串.

  1. The variable is a scalar. The value is a string.

for my $line (split(/^/m, $buffer)) {
    ...
}

但为什么不一次读一行.

But why not just read it a line at a time.

open(my $fh, '<', $filename)
    or error_out("Error opening $filename: $!");

while (my $line = <$fh>) {
    ...
}

这篇关于读取大文件 (Perl) 后如何使用 SCALAR 逐行读取?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆