#!/opt/perl/bin/perl-w
Use strict;
Use DIGEST::MD5 QW (MD5 md5_hex md5_base64);
#校验文件函数
Sub Calc_md5_hex () {
My ($file _name, $ctx, $MD 5);
($file _name) = @_;
Open (FileHandle, $file _name) or die "Can ' t open/' $file _name/': $!";
$ctx = digest::md5->new;
Binmode (FileHandle);
$ctx->addfile (*filehandle) | | Die "$!/n";
$MD 5 = $ctx->hexdigest;
Close FileHandle;
return $MD 5;
}
Sub Calc_md5_ascii () {
My ($file _name, $ctx, $MD 5);
($file _name) = @_;
Open (FileHandle, $file _name) or die "Can ' t open/' $file _name/': $!";
$ctx = digest::md5->new;
#binmode (FileHandle);
$ctx->addfile (*filehandle) | | Die "$!/n";
$MD 5 = $ctx->hexdigest;
Close FileHandle;
return $MD 5;
}
#定义目录路径
My $dirhandle = $ARGV [0];
#my $file _only = $ARGV [1]; #定义是否只是文件测试, to validate a single file call
if (-f $dirhandle) {
My $file _md5;
if (-t $dirhandle) {
$file _md5 = &calc_md5_ascii ($dirhandle);
}elsif (-b $dirhandle) {
$file _md5 = &calc_md5_hex ($dirhandle);
}
Print "Start calculating file MD5 value:/n${dirhandle}/n/t[${file_md5}][md5_hex]/n";
Exit 0;
}elsif (-D $dirhandle) {
My $file _md5;
Print "Start verifying all Files under directory:/n";
Opendir (DH, "$dirhandle") or die "Can ' t oprn dir/' $dirhandle/': $!";
foreach My $file (Readdir DH) {
$file = $dirhandle. ' /'. $file;
if (-f $file) {
Next if ($file =~ m{/.$} | | $file =~ m{/. $} || -L $file);
if (-t $file) {
#print "Calculate md5!/n according to text file";
$file _md5 = &calc_md5_ascii ($file);
Print "Start calculating file MD5 value:/n${file}/n/t[${file_md5}][md5_ascii]/n";
}elsif (-b $file) {
#print "Calculate md5!/n in binary file";
$file _md5 = &calc_md5_hex ($file);
Print "Start calculating file MD5 value:/n${file}/n/t[${file_md5}][md5_hex]/n";
}else{
Print "does not recognize whether the file is binary or text, and calculates!/n in binary file";
$file _md5 = &calc_md5_hex ($file);
Print "Start calculating file MD5 value:/n${file}/n/t[${file_md5}][md5_hex]/n";
}
}
}
Closedir DH;
}