Search code examples
perlmd5file-comparison

Comparing two files using perl md5


I wanted to run a code that continuosuly checks if a file exits if it exists then checks the files' MD5 against the previous MD5 . If there is some changes then it executes some code. But the perl MD% seems to be changing every time I call the hexdigest for the same file. Does MD5 change everytime ?

I intially had

$md5 = Digest::MD5->new; 

before while(1)

If this is not how it is to be done is there anything else to achieve my intentions ? Thanks

while(1)
{
    if(!(-e $config_file)){
            next;
    }else{
            $md5 = Digest::MD5->new;
            $md5->addpath($config_file);
            print "<->";
            print $md5->hexdigest;

            $value=($digest eq $md5->hexdigest ? 1 : 0);
            if($value==1)
            {
                    next;
            }else
            {
                    $digest=$md5->hexdigest;
            }
    }
}

Solution

  • The hexdigest operation is read-once, meaning that after you execute it, the value is reset. It can be read only once, but you attempt to read it twice. Store it in a temporary when you read it the first time.

    From the documentation (my emphasis):

    $md5->digest

    Return the binary digest for the message. The returned string will be 16 bytes long.

    Note that the digest operation is effectively a destructive, read-once operation. Once it has been performed, the Digest::MD5 object is automatically reset and can be used to calculate another digest value. Call $md5->clone->digest if you want to calculate the digest without resetting the digest state.

    $md5->hexdigest

    Same as $md5->digest, but will return the digest in hexadecimal form. The length of the returned string will be 32 and it will only contain characters from this set: '0'..'9' and 'a'..'f'.