Search code examples
perlfilefile-find

Perl Find - No such file or directory


I am using File::Find and file i/o on a text file to parse a series of directories and move the contents into a new folder. It is a simple script (see below):

#!/usr/bin/perl

use strict;
use warnings;
use File::Find;
use File::Copy;

my $dir = "/opt/CollectMinderDocuments/coastalalglive"; #base directory for Coastal documents

#read file that contains a list of closed IDs
open(MYDATA, "Closed.txt");

mkdir("Closed");

while(my $line = <MYDATA>) {
  chomp $line;
  my $str = "$dir" . "/Account$line";
  print "$str\n";
  find(\&move_documents, $str);
}
sub move_documents {
  my $smallStr = substr $File::Find::name, 43;
  if(-d) {
    #system("mkdir ~/Desktop/Closed/$smallStr");
    print "I'm here\n";
    system("mkdir /opt/CollectMinderDocuments/coastalalglive/Closed/$smallStr");
    #print "Made a directory: /opt/CollectMinderDocuments/coastalalglive/Closed/$smallStr\n";
  }
  else {
    print "Now I'm here\n";
    my $smallerStr = substr $File::Find::dir, 43;
    my $temp = "mv * /opt/CollectMinderDocuments/coastalalglive/Closed/$smallerStr/";
    system("$temp");
  }
}

The text file contains a list of numbers:

1234
2805
5467

The code worked when I executed it last month, but it is now returning a "file or directory not found" error. The actual error is "No such file or directoryerDocuments/coastalalglive/Account2805". I know all of the directories it is searching for exist. I have manually typed in one of the directories, and the script executes fine:

find(\&move_documents, "/opt/CollectMinderDocuments/coastalalglive/Account2805/");

I am not sure why the error is being returned. Thanks in advance for the help.


Solution

  • Your error:

    "No such file or directoryerDocuments/coastalalglive/Account2805"
    

    Seems to imply that there is an \r that was not removed by your chomp. That will happen when transferring files between different file systems, where the file contains \r\n as line endings. The real error string would be something like:

    /opt/CollectMinderDocuments/coastalalglive/Account2805\r: No such file or directory
    

    Try changing chomp $line to $line =~ s/[\r\n]+$//; instead, and see if that works.

    Also:

    my $temp = "mv * /opt/CollectMinderDocuments/coastalalglive/Closed/$smallerStr/";
    system("$temp");
    

    Is very wrong. The first non-directory file in that loop will move all the remaining files (including dirs? not sure if mv does that by default). Hence, subsequent iterations of the subroutine will find nothing to move, also causing a "Not found" type error. Though not one caught by perl, since you are using system instead of File::Copy::move. E.g.:

    move $_, "/opt/CollectMinderDocuments/coastalalglive/Closed/$smallerStr/" or die $!;