Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:


Script 1, stand alone script passing the name of a zip file:
use Digest::SHA1; $sha1 = Digest::SHA1->new; $fhIN = $ARGV[0]; open(IN,$fhIN) || die "\ncan open file for input"; binmode IN; $sha1->addfile(IN); $digest = $sha1->hexdigest; print "$digest\n";
Output:50bd187a208112091b035c62209baf9742c243bd
script 2, part of a CGI, passing the path to the same file as above:
sub generateDigest{ my ($file) = @_; my $sha1 = Digest::SHA1->new; open(FILE, $file) || die; binmode FILE; $sha1->addfile(*FILE); close(FILE); my $digest = $sha1->hexdigest; warn "$digest"; return $digest; }
Output: 7ba6487fefcc4467b21deccac79b38d7d3b69bf2
Why the difference?

Replies are listed 'Best First'.
Re: Digest::Sha1 differences
by moritz (Cardinal) on May 19, 2010 at 13:25 UTC
    Read the documentation again:
    $sha1->addfile(*FILE);
    

    (Emphasis by me). In one of the cases you forgot the *

    Perl 6 - links to (nearly) everything that is Perl 6.
      In one of the cases you forgot the *

      Interestingly, I don't get any difference in SHA1 (with or without the * — though the latter doesn't work with strictures of course, i.e. it gives Bareword "IN" not allowed while "strict subs" in use).

      #!/usr/bin/perl -l #use strict; use warnings; use Digest::SHA1; my $fname = $ARGV[0]; my $sha1; open(IN, $fname) || die "can't open '$fname' for input: $!"; binmode IN; $sha1 = Digest::SHA1->new; $sha1->addfile(IN); print $sha1->hexdigest; open(IN, $fname) || die "can't open '$fname' for input: $!"; binmode IN; $sha1 = Digest::SHA1->new; $sha1->addfile(*IN); print $sha1->hexdigest; open(my $fhIN, $fname) || die "can't open '$fname' for input: $!"; binmode $fhIN; $sha1 = Digest::SHA1->new; $sha1->addfile($fhIN); print $sha1->hexdigest; system 'sha1sum', $fname;

      Output for a file "foo" containing "bar\n":

      $ ./840698.pl foo e242ed3bffccdf271b7fbaf34ed72d089537b42f e242ed3bffccdf271b7fbaf34ed72d089537b42f e242ed3bffccdf271b7fbaf34ed72d089537b42f e242ed3bffccdf271b7fbaf34ed72d089537b42f foo

      Anyhow, to avoid the confusion, the OP could've used a lexical file handle, as shown in the third variant above.

        So you see no difference? Weird! I'm using a zip file of 60mb in my example. I'm on perl 5.8 on a sun solaris server. COuld there be some sort of problem relating to the size of the source file I want to make a digest of? Thanks
      thank you, can you tell me what the first example is creating a digest of? the file name?
        If it reads from the handle as long as it can, it hashes the empty string.

        But you'd have to look into the source to find out for sure.