Luke
Luke

Reputation: 1077

Identifying the difference between ordinary folders and "."/".." folders

I'm writing a Perl script to automatically copy PDFs from a folder.

Users are unable to access folders they don't have permission for so they don't accidentally gain access to any information they aren't supposed to.

I have a rough mock-up which works except for one bug: it keeps seeing the . and .. folders and opens them entering infinite loops.

The following conditional statement checked to see the file was a PDF, which would then pass to my copyPDF, which checks for exceptions and then copies the file; otherwise it passes and tries to open as a folder if a folder scans that content and repeats.

I've tried a number of ways to ignore the . and .. but it always leads to ignoring all other subfolders as well. Has anyone got a work around?

if ($file =~ /\.pdf$/i) {
  print "$file is a pdf\n";
  $fileLocation = "$directoryName/$file";
  copyPDF("$fileLocation", "$file");
}
elsif ($file == '.') {
  #print "argh\n";
}
else {
  $openFolder = "$directory/$file";
  print "*$openFolder";
  openNextDirectory("$openFolder");
}

Upvotes: 2

Views: 230

Answers (3)

David
David

Reputation: 6561

use the File::Find module

use File::Find;
use File::Copy;

my $directory = 'c:\my\pdf\directory';
find(\&pdfcopy, $directory);

sub pdfcopy() {
    my $newdirectory = 'c:\some\new\dir';
    return if ($File::Find::name !~ /\.pdf$/i);
    copy($File::Find::name, $newdirectory) or 
    die "File $File::Find::name cannot be copied: !";
}

Upvotes: -3

uptownnickbrown
uptownnickbrown

Reputation: 997

This old question has some great answers that address this and similar questions:

How can I copy a directory recursively and filter filenames in Perl?

Upvotes: 2

ikegami
ikegami

Reputation: 386541

Always use use strict; use warnings;!!!

$file == '.'

produces

Argument "." isn't numeric in numeric eq (==)

because you are asking Perl to compare two numbers. You should be using

$file eq '.'

See perldoc perlop for more information about perl's operators.

Upvotes: 4

Related Questions