Perl: Calculate the md5 sum of a file

Articles may may have files attached at the end of the post

This code sample shows how one could compute the md5sum of a file using Perl's Digest::MD5 module.

  1. #!/usr/bin/env perl
  2.  
  3. use warnings;
  4. use strict;
  5.  
  6. use Digest::MD5;
  7.  
  8. sub md5sum{
  9.   my $file = shift;
  10.   my $digest = "";
  11.   eval{
  12.     open(FILE, $file) or die "Can't find file $file\n";
  13.     my $ctx = Digest::MD5->new;
  14.     $ctx->addfile(*FILE);
  15.     $digest = $ctx->hexdigest;
  16.     close(FILE);
  17.   };
  18.   if($@){
  19.     print $@;
  20.     return "";
  21.   }
  22.   return $digest;
  23. }
  24. sub usage{
  25.   print "usage: ./md5sum.pl filename\n";
  26.   exit 1;
  27. }
  28. if($#ARGV + 1 != 1){
  29.   usage();
  30.  }
  31. my $fname = $ARGV[0];
  32. my $md5 =  md5sum($fname);
  33. if($md5 ne ""){
  34.   print $md5." ".$fname."\n";
  35. }else{
  36.   exit 1;
  37. }
  38.  
  39. exit 0;

will output:

$  ./md5sum.pl md5sum.pl 
e8c6c6f7995e7a24140f048d29f8fd6c md5sum.pl
$ ./md5sum.pl missingfile
[ERROR] md5sum: Can't find file missingfile
AttachmentSize
md5sum.pl.txt593 bytes

Cool, but I think using

Cool, but I think using md5sum is easier. If you need it in PERL use exec command.