Bvcdi
Bvcdi

Reputation: 1

MD5 hexdigest verification with a string

I am having a problem comparing the result from the file_md5_hex( $dir ) subroutine with a string read from a file. When I print they are both the same, but when I compare them in a if I get all the time equal regardless of the value they have.

elsif ( -f $dir )
{
 if($dir ne "$mydir.txt" && $dir ne "log.txt")
 {
  my $filename = "$mydir.txt";
  open(my $fh, '<:encoding(UTF-8)', $filename)
  or die "Could not open file '$filename' $!";
  print FILE "$dir -> ";
  while (my $row = <$fh>)
  {
   chomp($row);
   if($row eq $dir)
     {
      my $hash = <$fh>;
      chomp($hash);
      print FILE "$hash = ";
      break;
     }
  }
  close $fh;
   my $md5 = file_md5_hex( $dir );
   print FILE "$md5\n";
   print FILE ref($md5);
   print FILE ref($hash);
   if( $md5 eq $hash )
   {
     print FILE "Hash ok!\n";
     }
   else
   {
     print FILERESULT "In $mydir file $dir is corrupted. Correct is $hash, calculated is $md5\n";
     print FILE "Hash Nok!\n";
   }
 }
}

In the log file I see that the 2 values $md5 and $hash are the same or different (depending on the case I simulate) but when I verify the program sees them as always equal. I think there might be a problem with the types of data but I don't know how to fix it.

Upvotes: 0

Views: 199

Answers (1)

UjinT34
UjinT34

Reputation: 4987

use strict to detect errors with variable names and scopes. $hash is not defined on if( $md5 eq $hash ) because my $hash = <$fh>; is out of scope. Declare my $hash before while (my $row = <$fh>) and set the value with $hash = <$fh>;

http://perldoc.perl.org/functions/my.html

Upvotes: 2

Related Questions