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

2.9k Views Asked by At

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 on a single line. Why isn't chomp removing the newlines from the file, like it's supposed to?

6

There are 6 best solutions below

3
On BEST ANSWER

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.)

0
On

You should check open for errors:

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

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;
0
On

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

1
On

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.