Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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;

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top