您的位置:宽带测速网 > 编程知识 > perl怎么读取文件内容到数组

perl怎么读取文件内容到数组

2025-06-23 19:25来源:互联网 [ ]

在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函数来关闭文件句柄。