Question

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;
            }
    }
}
Was it helpful?

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'.

OTHER TIPS

I'm not seeing a problem with this. Here's a shorter version of what you're trying to do:

#!/usr/bin/env perl 

use strict; 

use Digest::MD5::File; 
my $config_file = '/tmp/test.txt'; 
my $digest; 

while ( 1 ) { 
    next if !-e $config_file; 

    my $md5 = Digest::MD5::File->new; 
    $md5->addpath( $config_file ); 

    print $md5->hexdigest . "\n"; 

    print '-' x20 . " digest changed"; 
    $digest = $md5->hexdigest; 
}

If you run the code, you'll see that the digest changes only the first time, when the $digest is assigned to the first time. After that, the digest does not change.

addpath appears to be provided by Digest::MD5::File rather than by Digest::MD5 itself, so I've changed the use statement from your example.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top