views:

322

answers:

3

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, though the use of chomp din't work.

+4  A: 

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?

Chris J
Instead of all that regex, just:md5 .bash_history | perl -lane 'print pop @F'(or shift @F if you are using md5sum).
Emil
@Emil: what regex? and instead of perl, |rev|cut -f 1 -d ' '|rev :)
ysth
+5  A: 

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
dlamblin
+1  A: 

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);
ysth
For debugging scalars I find it easier to just do `print "[$a] [$b]";`
friedo
@friedo: that works...unless you have tabs vs. spaces, or nul chars, etc.
ysth