How can I compare md5 checksums in Perl?
I'm trying to compare the checksum value of a file.
One variable $a
has the checksum (output of md5sum
command, only the hexadecimal part)
and the same value is in variable $b
.
If I do ($a == $b
), I am getting an error, but if I do ($a eq $b)
it gives not equal.
Thanks for your answers, it worked in string comparison after trimming the white spaces, th开发者_如何学Pythonough the use of chomp din't work.
You are comparing strings, not numbers, so do use eq
.
Also use lc()
, and chomp()
or $a=~s/^\s+//;$a=~s/\s+$//;
.
You do have the pretty decent option of converting the input to numbers with hex()
and using ==
.
Try:
if (hex($a) == hex($b)){}
This all depends on how well you're handling the output of your md5sum
command. Mine looks like this:
dlamblin$ md5 .bash_history
MD5 (.bash_history) = 61a4c02cbd94ad8604874dda16bdd0d6
So I process it with this:
dlamblin$ perl -e '$a=`md5 .bash_history`;$a=~s/^.*= |\s+$//g;print $a,"\n";'
61a4c02cbd94ad8604874dda16bdd0d6
Now I do notice that hex()
has an integer overflow error on this so you'll want to use 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
Make sure that your strings don't have new-lines or other characters at the end. If in doubt, chomp()
both then compare. Also (just to cover off the exceedingly obvious), they are both using the same case to encode the hex chars?
If ($a eq $b) is false, then they are indeed not equal. If you've ruled out obvious differences like "filename: " on one of them, you need to look for whitespace or nonprintable character differences. The easy way to do that is:
use Data::Dumper;
$Data::Dumper::Useqq=1;
print Dumper($a);
print Dumper($b);
精彩评论