How to compare md5 checksums in Perl?
I am trying to compare the checksum value of a file. One variable $a
has a checksum (command output md5sum
, hex part only) and the same value is in the variable $b
.
If I do ( $a == $b
) I get an error, but if I do ($a eq $b)
it doesn't equal.
Thanks for your answers, it worked in comparing strings after trimming whitespace, although using chomp din't doesn't work.
You are comparing strings, not numbers, so use eq
.
Also use lc()
and chomp()
or $a=~s/^\s+//;$a=~s/\s+$//;
.
You have a pretty decent option for converting input to numbers with hex()
and with ==
. Try:
if (hex($a) == hex($b)){}
It all depends on how well you handle the output of your command md5sum
. Mine looks like this:
dlamblin$ md5 .bash_history
MD5 (.bash_history) = 61a4c02cbd94ad8604874dda16bdd0d6
So I handle it with this:
dlamblin$ perl -e '$a=`md5 .bash_history`;$a=~s/^.*= |\s+$//g;print $a,"\n";'
61a4c02cbd94ad8604874dda16bdd0d6
Now I notice I hex()
have an integer overflow error, so you will wantuse bigint;
dlamblin$ perl -e '
$a=`md5 .bash_history`;$a=~s/^.*= |\s+$//g;print hex($a),"\n";'
Integer overflow in hexadecimal number at -e line 1.
1.29790550043292e+38
dlamblin$ perl -Mbigint -e '
$a=`md5 .bash_history`;$a=~s/^.*= |\s+$//g;print hex($a),"\n";'
129790550043292010470229278762995667158
source to share
If ($ a eq $ b) is false, then they really are not equal. If you've ruled out obvious differences like "filename:" on one of them, you need to look for spaces or non-printable character differences. An easy way to do it:
use Data::Dumper;
$Data::Dumper::Useqq=1;
print Dumper($a);
print Dumper($b);
source to share