2


I am using Digest::MD5 module and in that hexdigest returning different value for windows and linux.

please help me in solving the issue.

use Digest::MD5;
my $ctx=Digest::MD5->new();
open RD, "input.txt";
$ctx->addfile(*RD);
close RD;
print $ctx->hexdigest;

input.txt file has below content:

hello

output: windows

5d41402abc4b2a76b9719d911017c592

output: Linux

af5597c29467a96523a70787c319f4db

Thanks,
Saravanan

RobEarl
  • 7,862
  • 6
  • 35
  • 50
Saravanan
  • 119
  • 10

2 Answers2

6

According to the comments given by the asker, the input.txt is generated in Windows and then is copied to Linux, then I believe the problem is caused by the difference between Windows and Linux end-of-line, in Windows end-of-line is '\r\n', in Linux '\n'.Therefore, using binmode() set the filehandler to binary mode should be able to fix this, as suggested in the examples of Digest::MD5.

This should fix the problem:

#!/usr/bin/perl

use warnings;
use strict;

use Digest::MD5;

open my $fh, '<', 'input.txt' or die "Cannot open input.txt: $!";
binmode $fh, ':raw'; # <==== NOTE this binmode()

my $md5 = Digest::MD5->new;
$md5->addfile($fh);
print $md5->hexdigest, "\n";
close $fh;
Lee Duhem
  • 14,695
  • 3
  • 29
  • 47
  • Thanks I tried its working after adding binmode in windows I have added binmode in windows and in linux i removed binmode now I am getting same value. – Saravanan Feb 28 '14 at 11:17
  • 2
    @Saravanan It is no need to remove the `binmode()` in your Windows version script. – Lee Duhem Feb 28 '14 at 11:27
  • 2
    You may prefer `binmode $file, ':raw'` to make the access mode explicit. In any case, `$file` is a poor name for anything. It could be a file name string, a file path string, or, unusually as here, a file handle. I suggest at least `$fn`, `$path`, `$fh`. – Borodin Feb 28 '14 at 13:28
  • @Borodin You are right, `$file` is a bad choose for a reference of file handler. Answer updated. – Lee Duhem Feb 28 '14 at 15:04
-1

That can be because each time the hash value changes, you can refer this http://en.wikipedia.org/wiki/MD5

flx
  • 14,146
  • 11
  • 55
  • 70
Programmer
  • 455
  • 5
  • 18