Reading from a directory fails

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • joeferns79
    New Member
    • Sep 2008
    • 37

    Reading from a directory fails

    I've got a script that's supposed to read files from a directory, and do pattern match on each file in the dir. If I run this script from within the dir that contains the files, it works fine but it fails to find any file if I run it from the parent dir.

    Code:
    #!/usr/bin/perl
    
    use strict;
    use warnings;
    
    opendir my $DIR, '/home/tester1/logs/' or die "opendir .: $!\n";
    print "$DIR\n";
    my @files = grep /\.log$/i, readdir $DIR;
    closedir $DIR;
    # print "Got ", scalar @files, " files\n";
    
    open my $out,'>',"report.txt";
    
    foreach my $file (@files) {
        open my $FILE, '<', $file or die "$file: $!\n";
        while (<$FILE>) {
           print $out $_ if /^<string to search>/;
    }
        close $FILE;
    }
    close $out;
    This is the output I get ...

    bash-4.1$ ./test.pl
    GLOB(0x200161f8 )
    test1.log: A file or directory in the path name does not exist.
    bash-4.1$
  • RonB
    Recognized Expert Contributor
    • Jun 2009
    • 589

    #2
    Here's my answer I posted on your crosspost at perlguru.

    readdir only returns the filename without its path. If you're not in the same directory as the path given to opendir, then you'll need to prepend that path to the filename in your open call.

    Please read the documentation for the readdir function.
    perldoc readdir

    Comment

    • joeferns79
      New Member
      • Sep 2008
      • 37

      #3
      Thanks, Ron! I appreciate it.

      Comment

      Working...