开发者

Why is my Perl program not reading from the input file?

开发者 https://www.devze.com 2023-02-11 18:20 出处:网络
I\'m trying to read in this file: Oranges Apples Bananas Mangos using this: open (FL, \"fruits\"); @fruits while(<FL>){

I'm trying to read in this file:

Oranges
Apples
Bananas
Mangos

using this:

open (FL, "fruits");
@fruits

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

print @fruits;

But I'm not getting any output. What am I missing here? I'm trying to store all the lines in the file into an array, and printing out all the contents开发者_JAVA技巧 on a single line. Why isn't chomp removing the newlines from the file, like it's supposed to?


you should always use :

use strict;
use warnings;

at the begining of your scripts.

and use 3 args open, lexical handles and test opening for failure, so your script becomes:

#!/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;


I'm guessing that you have DOS-style newlines (i.e., \r\n) in your fruits file. The chomp command normally only works on unix-style (i.e., \n.)


You're not opening any file. FL is a file handle that never is opened, and therefore you can't read from it.

The first thing you need to do is put use warnings at the top of your program to help you with these problems.


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

my $fh = IO::File->new('fruits', 'r') or die "$!\n";
my @fruits = grep {s/\n//} $fh->getlines;
print Dumper \@fruits;

that's nice and clean


You should check open for errors:

open( my $FL, '<', 'fruits' ) or die $!;
while(<$FL>) {
...


1) You should always print the errors from IO. `open() or die "Can't open file $f, $!";

2) you probably started the program from different directory from where file "fruits" is

0

精彩评论

暂无评论...
验证码 换一张
取 消