in reply to Can I abstract these blocks into a function call?

I'd roll it into a sub and pass in the mode etc:

sub calcDigest { my ($fileName, $mode, $opt_u, %family) = @_; my $inFile; if (!open ($inFile, '<', $fileName)) { print STDERR "$0 : cannot open file \"$fileName\"\n"; return 0; } binmode $inFile; my $dObj = Digest::SHA->new ($mode); my $digest; if ($family{"sha$mode"}) { $dObj->addfile ($inFile); $digest = $dObj->digest; my $ps = unpack ("B*", $digest); while (length ($ps) < 160) {$ps = "0$ps";} print "sha$mode($fileName)= $ps\n"; seek (FILE, 0, 0); } if ($family{"sha${mode}_hex"}) { $dObj->addfile ($inFile); $digest = lc ($dObj->hexdigest); if ($opt_u) {$digest = uc ($digest);} print "sha${mode}_hex($fileName)= $digest\n"; seek (FILE, 0, 0); } if ($family{"sha${mode}_b64"}) { $dObj->addfile ($inFile); $digest = $dObj->b64digest; while (length ($digest) % 4) {$digest .= '=';} print "sha${mode}_b64($fileName)= $digest\n"; } close ($inFile); }

Note that the original code printed sha1($fileName)= for the sha256 case in the $do_256 branch. I assumed that was copy and paste error and 'corrected' it.

Update: type globs removed per jwkrahn's reply (doh!).


True laziness is hard work

Replies are listed 'Best First'.
Re^2: Can I abstract these blocks into a function call?
by jwkrahn (Abbot) on Mar 27, 2010 at 01:54 UTC
    my $inFile; ... if (!open ($inFile, '<', $fileName)) { ... if ($family{"sha$mode"}) { $dObj->addfile (*$inFile); ... if ($family{"sha${mode}_hex"}) { $dObj->addfile (*$inFile); ... if ($family{"sha${mode}_b64"}) { $dObj->addfile (*$inFile); ...

    You can't use a typeglob with a lexical variable.    Remove the '*' from in front of $inFile.

Re^2: Can I abstract these blocks into a function call?
by dwhite20899 (Friar) on Mar 27, 2010 at 23:41 UTC
    That's what I was thinking of, and I just couldn't pull it together - sweet! Now I have to get rid of the seeks, and not reread the file every time.