1

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?

Waffles
  • 121
  • 3
  • 7

6 Answers6

6

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;
Toto
  • 89,455
  • 62
  • 89
  • 125
4

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

Alex Howansky
  • 50,515
  • 8
  • 78
  • 98
  • That was exactly it. Thank you so much. I've been banging my head against this for the past half hour. – Waffles Feb 18 '11 at 19:14
  • Are you psychic? +1 for the successful guess. – Linus Kleen Feb 18 '11 at 19:16
  • 1
    `perldoc _f chomp` : chomp removes any trailing string that corresponds to the current value of `$/`. It works well under linux (default is `\n`), windows (`\r\n`) and mac (`\r`). – Toto Feb 18 '11 at 19:26
3

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.

Andy Lester
  • 91,102
  • 13
  • 100
  • 152
  • Sorry, I didn't add in the open file command initially to this post. It was always there in the program, I just omitted it from this problem. – Waffles Feb 18 '11 at 18:59
1
#!/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

BadFileMagic
  • 701
  • 3
  • 7
0

You should check open for errors:

open( my $FL, '<', 'fruits' ) or die $!;
while(<$FL>) {
...
sid_com
  • 24,137
  • 26
  • 96
  • 187
0

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

DVK
  • 126,886
  • 32
  • 213
  • 327