kaye
kaye

Reputation: 47

To parse multiple files in Perl

Please correct my code, I cannot seem to open my file to parse. The error is this line open(my $fh, $file) or die "Cannot open file, $!"; Cannot open file, No such file or directory at ./sample.pl line 28.

use strict;
my $dir = $ARGV[0];

my $dp_dpd = $ENV{'DP_DPD'};

my $log_dir = $ENV{'DP_LOG'};
my $xmlFlag = 0;
my @fileList = "";

my @not_proc_dir = `find $dp_dpd -type d -name "NotProcessed"`;

#print "@not_proc_dir\n";


foreach my $dir (@not_proc_dir) {
        chomp ($dir);
        #print "$dir\n";

    opendir (DIR, $dir) or die "Couldn't open directory, $!";
    while ( my $file = readdir DIR) {
            next if $file =~ /^\.\.?$/;
            next if (-d $file);
       #   print "$file\n";
            next if $file eq "." or $file eq "..";
                    if ($file =~ /.xml$/ig) {
                     $xmlFlag = 1;
                     print "$file\n";
                     open(my $fh, $file) or die "Cannot open file, $!";
                    @fileList = <$fh>;
                    close $file;


                    }

            }
            closedir DIR;

}

Upvotes: 0

Views: 99

Answers (1)

Dada
Dada

Reputation: 6626

Quoting readdir's documentation:

If you're planning to filetest the return values out of a readdir, you'd better prepend the directory in question. Otherwise, because we didn't chdir there, it would have been testing the wrong file.

Your open(my $fh, $file) should therefore be open my $fh, '<', "$dir/$file" (note how I also added '<' as well: you should always use 3-argument open).

Your next if (-d $file); is also wrong and should be next if -d "$dir/$file";


Some additional remarks on your code:

  • always add use warnings to your script (in addition to use strict, which you already have)

  • use lexical file/directory handle rather than global ones. That is, do opendir my $DH, $dir, rather than opendir DH, $dir.

  • properly indent your code (if ($file =~ /.xml$/ig) { is one level too deep; it makes it harder to read you code)

  • next if $file =~ /^\.\.?$/; and next if $file eq "." or $file eq ".."; are redundant (even though not technically equivalent); I'd suggest using only the latter.

  • the variable $dir defined in my $dir = $ARGV[0]; is never used.

Upvotes: 8

Related Questions