为什么我的Perl程序没有从输入文件中读取?

Waf*_*les 1 perl file-io chomp

我正在尝试阅读此文件:

Oranges
Apples
Bananas
Mangos
Run Code Online (Sandbox Code Playgroud)

使用这个:

open (FL, "fruits");
@fruits

while(<FL>){
chomp($_);
push(@fruits,$_);
}

print @fruits;
Run Code Online (Sandbox Code Playgroud)

但我没有得到任何输出.我在这里错过了什么?我正在尝试将文件中的所有行存储到一个数组中,并在一行中打印出所有内容.为什么不选择从文件中删除换行符,就像它应该的那样?

Tot*_*oto 5

你应该总是使用:

use strict;
use warnings;
Run Code Online (Sandbox Code Playgroud)

在脚本的开头.

并使用3 args open,lexical handle和test opening for failure,因此你的脚本变为:

#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;

my @fruits;
my $file = 'fruits';
open my $fh, '<', $file or die "unable to open '$file' for reading :$!";

while(my $line = <$fh>){
    chomp($line);
    push @fruits, $line;
}

print Dumper \@fruits;
Run Code Online (Sandbox Code Playgroud)