所以我希望我的perl文件读取包含两行的文件:
1 10 4
6 4
我希望第一行是@setA,第二行是@setB。如果不进行硬编码,我该怎么做?
答案 0 :(得分:2)
您将打开文件以获取所谓的文件句柄(通常名为$fh
),读取内容并关闭文件句柄。这样做涉及调用open
,readline
和close
。
注意readline也有一个特殊的语法,如<$fh>
。阅读线通常遵循成语:
while ( <$fh> ) {
# the line is in the $_ variable now
}
然后解决每一行你使用split
function。
偶尔有用的另一个是chomp
。
这应该让你开始。
答案 1 :(得分: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 )
答案 2 :(得分: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;