Perl – Get the md5 hash for a file
Get the MD5 hash for a file on the command line, using Digest::MD5
usage: ./md5sum.pl [filename] [-f] -f do not display filename
[perl]
use warnings;
use strict;
use Digest::MD5;
sub md5sum
{
my $file = shift;
my $digest = “”;
eval{
open(FILE, $file) or die “Can’t find file $file\n”;
my $ctx = Digest::MD5->new;
$ctx->addfile(*FILE);
$digest = $ctx->hexdigest;
close(FILE);
};
if($@){
print $@;
return “”;
}
return $digest;
}
sub usage
{
print “usage: ./md5sum.pl [filename] [-f]\n”;
print “\t-f\tdo not display filename\n”;
exit 1;
}
if (($#ARGV + 1 != 1) && ($#ARGV + 1 != 2)){
usage();
}
my $fname = $ARGV[0];
my $withfil = $ARGV[1];
my $md5 = md5sum($fname);
if($md5 ne “”){
if ($withfil) {
print “$md5\n”;
} else {
print $md5.” “.$fname.”\n”;
}
}else{
exit 1;
}
exit 0;
[/perl]