Perl: Calculate the md5 sum of a file
Articles may may have files attached at the end of the post
Submitted by chantra on Sat, 04/12/2008 - 17:45
This code sample shows how one could compute the md5sum of a file using Perl's Digest::MD5 module.
- #!/usr/bin/env perl
- use warnings;
- use strict;
- use Digest::MD5;
- sub md5sum{
- my $digest = "";
- eval{
- my $ctx = Digest::MD5->new;
- $ctx->addfile(*FILE);
- $digest = $ctx->hexdigest;
- };
- if($@){
- print $@;
- return "";
- }
- return $digest;
- }
- sub usage{
- print "usage: ./md5sum.pl filename\n";
- exit 1;
- }
- if($#ARGV + 1 != 1){
- usage();
- }
- my $fname = $ARGV[0];
- my $md5 = md5sum($fname);
- if($md5 ne ""){
- }else{
- exit 1;
- }
- exit 0;
will output:
$ ./md5sum.pl md5sum.pl e8c6c6f7995e7a24140f048d29f8fd6c md5sum.pl $ ./md5sum.pl missingfile [ERROR] md5sum: Can't find file missingfile
| Attachment | Size |
|---|---|
| md5sum.pl.txt | 593 bytes |












