perl 从标量变量中逐行读取

perl read line-by-line from scalar variable

通过抓取网站,我在标量变量 $res 中有一个 html 文件。 我想逐行读取 $res 中的 html 文件。例如, while (my $line = )...

我是否需要将 $res 打印到文本文件,然后读入文本文件?

您可以使用 IO::Scalar 模块。

man IO::Scalar :

use 5.005;
use IO::Scalar;
$data = "My message:\n";

### Open a handle on a string, read it line-by-line, then close it:
$SH = new IO::Scalar $data;
while (defined($_ = $SH->getline)) {
    print "Got line: $_";
}

while(<$SH>) 也有效。

针对the Y part of this problem,是的,您可以将标量变量视为输入源并使用Perl 的输入处理功能。您只是 open 对变量的引用:

open my $fh, '<', $res;
my $header = <$fh>;        # first "line" of $res
while (my $line = <$fh>) { # next "line" of $res
    ...
}