#!/usr/bin/perl
use File::Find;
use File::Basename;
use File::Copy;

$HOME_dir = `echo \$HOME`;
chomp $HOME_dir; #刪去換行符
$dst_dir = $HOME_dir."/Desktop/tmp/"; #目的路徑
$pic_dir = $HOME_dir."/magic/dir"; #圖片檔目錄
$text_filename = "list2.txt";

sub find_file {
    $dir = $File::Find::dir;
    $fname = $File::Find::name;
    $name = $_;
    $basename = fileparse($fname, qr/\..*/);
    next if ($name =~ /^\./);
    next if (-d $name);
    $num = $basename;
    if ($num ne " ") {
        $HASH{$num} = $fname;
    }
}
#印出HASH內容(用於驗證)
sub print_hash_data {
    print "-----Print HASH Data-----\n";
    while(($key, $value) = each %HASH) {
        print "$key => $value\n";
    } 
}
sub print_file_count {
    $command = "find $pic_dir -type f | wc -l";
    $count = `$command`;
    print "Total find files:$count\n";
}
#測試tmp目錄是否存在,如果不在就建立目錄
sub test_tmp_dir {
    mkdir($dst_dir) unless (-d $dst_dir);
}
#比對 text.txt 和HASH 是否符合並copy到tmp目錄 
sub compare_and_copy {
    open FILE, $text_filename or die "Can't open $text_filename";
    while (<FILE>) {
        chomp;
        print "Part Num:$_\n";
        $p_num = $_;
        if (exists ($HASH{$p_num})) {
            $pic_name = $HASH{$p_num};
            $pic_basename = basename($pic_name);
            print "Pic name:$pic_basename\n";
            $newfile = $dst_dir.$pic_basename;
            print "\tCopy to:$newfile\n";
            copy ($pic_name, $newfile);
        } else {
            print "\t---No math!---\n";
        }
    }
}
find(\&find_file, $pic_dir); #執行遞迴
#print_hash_data();
test_tmp_dir();
compare_and_copy();
print_file_count();
