perl怎么读取文件内容到数组
在Perl中,可以使用open
函数打开文件,并使用<>
操作符逐行读取文件内容到数组中。下面是一个示例代码:
my $file = "example.txt";open(my $fh, "<", $file) or die "Cannot open file: $!";my @lines = <$fh>;close($fh);foreach my $line (@lines) {chomp($line); # 去除每行末尾的换行符print "$line\n";}
在上面的示例中,首先使用open
函数打开名为example.txt
的文件,然后使用<>
操作符将文件内容逐行读取到@lines
数组中。最后,使用foreach
循环遍历数组并打印每行内容。
需要注意的是,在使用完文件之后需要调用close
函数来关闭文件句柄。