olala
olala

Reputation: 4436

perl: canot open file within a loop

I am trying to read in a bunch of similar files and process them one by one. Here is the code I have. But somehow the perl script doesn't read in the files correctly. I'm not sure how to fix it. The files are definitely readable and writable by me.

#!/usr/bin/perl
use strict;
use warnings;

my @olap_f = `ls /full_dir_to_file/*txt`;

foreach my $file (@olap_f){
    my %traits_h;

    open(IN,'<',$file) || die "cannot open $file";

    while(<IN>){
        chomp;
        my @array = split /\t/;
        my $trait = $array[4];
        $traits_h{$trait} ++;
    }
    close IN;

}  

When I run it, the error message (something like below) showed up:

cannot open /full_dir_to_file/a.txt

Upvotes: 0

Views: 97

Answers (2)

G. Cito
G. Cito

Reputation: 6378

I'll add a quick plug for IO::All here. It's important to know what's going on under the hood but it's convenient sometimes to be able to do:

use IO::All;
my @olap_f = io->dir('/full_dir_to_file/')->glob('*txt');

In this case it's not shorter than @cjm's use of glob but IO::All does have a few other convenient methods for working with files as well.

Upvotes: 1

cjm
cjm

Reputation: 62099

You have newlines at the end of each filename:

my @olap_f = `ls ~dir_to_file/*txt`;
chomp @olap_f; # Remove newlines

Better yet, use glob to avoid launching a new process (and having to trim newlines):

my @olap_f = glob "~dir_to_file/*txt";

Also, use $! to find out why a file couldn't be opened:

open(IN,'<',$file) || die "cannot open $file: $!";

This would have told you

cannot open /full_dir_to_file/a.txt
: No such file or directory

which might have made you recognize the unwanted newline.

Upvotes: 6

Related Questions