1

所以我希望我的 perl 文件读取包含两行的文件:

1 10 4
6 4

我希望第一行是@setA,第二行是@setB。我如何在不硬编码的情况下做到这一点?

4

3 回答 3

2

您将打开文件以获得所谓的文件句柄(通常命名为$fh),读取内容,然后关闭文件句柄。这样做涉及调用openreadlineclose

注意 readline 也有一个特殊的语法,比如<$fh>. 阅读台词通常遵循成语:

while ( <$fh> ) {
    # the line is in the $_ variable now
}

然后处理每一行你会使用split函数

另一个偶尔有用的是chomp.

那应该让你开始。

于 2012-05-17T08:11:30.253 回答
1
my $setA = <$fh>;   # "1 10 4"
my $setB = <$fh>;   # "6 4"

或者

my @setA = split ' ', scalar(<$fh>);   # ( 1, 10, 4 )
my @setB = split ' ', scalar(<$fh>);   # ( 6, 4 )
于 2012-05-17T16:59:47.307 回答
0
use strict;
use warnings;
use autodie qw(:all);

open my $file, '<', 'file.txt';

my @lines = <$file>;
my @setA = $lines[0];
my @setB = $lines[1];

print("@setA");
print("@setB");

close $file;
于 2012-05-17T08:22:44.890 回答