Saturday, February 8, 2014

InOneFolderNotTheOther.pl

Found this Perl script on a laptop I'm prepping to hand over...  I remember hacking it together, a simple "what folders are in one folder but not the other", kind of a half-baked folder sync.

#!/usr/bin/perl

$dir1 = $ARGV[0];
$dir2 = $ARGV[1];


@a = getFilesInDir($dir1);
@b = getFilesInDir($dir2);

print "In $dir1 ::\n";
foreach $thing (findElementsInANotB(a,b)){
print "$thing\n";
}

print "--\n";

@a = getFilesInDir($dir2);
@b = getFilesInDir($dir1);

print "In $dir2 \n";
foreach $thing (findElementsInANotB(a,b)){
print "$thing\n";
}


exit;

@a = ("1","2");
@b = ("2","3");


sub getFilesInDir {
my($dirname) = @_;
my $file;
my @files;
opendir(DIR,"$dirname") or print "can't open $dirname";
while(defined($file= readdir(DIR))) {
if($file ne "." && $file ne ".."){
push @files, $file;
}
}
closedir(DIR);
return @files;
}




sub findElementsInBoth{
my($refA, $refB) = @_;

my @a = @$refA;
my @b = @$refB;
my %hashB = ();
my @result = ();
my $thing;

foreach $thing(@b){
$hashB{$thing} = 1;
}
foreach $thing(@a){
if(defined($hashB{$thing})){
push @result, $thing;
}
}
return @result;
}

sub findElementsInANotB{
my($refA, $refB) = @_;

my @a = @$refA;
my @b = @$refB;
my %hashB = ();
my @result = ();
my $thing;

foreach $thing(@b){
$hashB{$thing} = 1;
}
foreach $thing(@a){
if(! defined($hashB{$thing})){
push @result, $thing;
}
}
return @result;
}

No comments:

Post a Comment