The following script gives me confusing results.
I've not delved into OOP before and am surprised when something
appears to work but gives wrong answers.
Explicitly Digest::MD5's md5_hex gives wrong answers if called as
Digest::MD5->md5_hex. OK, I've figured out that it shouldn't be called
like that after the fact but am surprised that it appeared to work,
throwing no warnings or errors.
Err I forget, Debian 4.0 Etch (mostly), Perl 5.8.4 $ CPU = P1.
root@/deb40a:~/perl.practice> md5sum md5_hex; ./md5_hex md5_hex;
./md5_hex -d md5_hex; ./md5_hex -o md5_hex # on one line
724d24ef7d8353f2061534850fd11bef md5_hex
724d24ef7d8353f2061534850fd11bef md5_hex
5e4c8a2bd461ae80cd9d0d08e1da12a3 md5_hex
724d24ef7d8353f2061534850fd11bef md5_hex
Elucidation will be appreciated.
Thanks,
Mike
#!/usr/bin/perl
# md5_hex 1/1/09 (c) Mike McClain
# return md5 as /usr/bin/md5sum
use strict; # this can be removed when all bugs are fixed
use warnings; # duplicates -w
use integer;
use Digest::MD5 qw(md5_hex); # md5_hex 32 bytes long
$|++; # unbuffered STDOUT
my $myDebug = 0;
my $useOO = 0;
my( $target, $calcdMD5);
## get CL switches
while( @ARGV && ($ARGV[0] =~ /-[do]/io) )
{ $myDebug = shift @ARGV if( @ARGV && ($ARGV[0] =~ /-d/io) );
$useOO = shift @ARGV if( @ARGV && ($ARGV[0] =~ /-o/io) );
}
# set debug from the CL as md5_hex -d3
$myDebug = substr($myDebug, 2) if( length($myDebug) > 2);
# print out the globals
if ( $myDebug && ($myDebug =~ /1/) )
{ print "\$myDebug = $myDebug.\n";
print "\$useOO = $useOO.\n";
print "\...@argv = @ARGV\n";
}
foreach( @ARGV)
{ $target = $_;
if( $useOO)
{ open(FILE, $target) or die "Can't open '$target': $!";
binmode(FILE);
print Digest::MD5->new->addfile(*FILE)->hexdigest, " $target\n";
close(FILE);
}
else
{ $calcdMD5 = cksum_file($target);
print $calcdMD5, " ", $target, "\n";
}
}
# ------- end of main -------------------
sub cksum_file # ($file)
{ # return md5_hex sum of file or 0 if file doesn't exist
my $file = shift;
my $digest;
local $/; # slurp mode
return '0' if( ! -e $file);
open INFILE, "<$file" || die "Unable to open $file: $! stopped ";
binmode(INFILE);
my $data = <INFILE> ;
close INFILE;
if ( $myDebug ) # this gives wrong answers
{ $digest = Digest::MD5->md5_hex($data); }
else
{ $digest = md5_hex($data); }
$digest;
}
__END__
--
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
http://learn.perl.org/