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

#!/usr/bin/perl $/=\1;while(<>){$c=($c<<1)+($c>>31)+($x>>2==3?0:ord);$x++}printf"%x",$ +c

I have fuddled with this trying to figure out exactly what is happening but I am at a loss.

UPDATED QUESTION

I orignally thought that if I could understand the script I could rewrite it as a sub that I could pass my $buffer and get back a hex representation and the actual result that I could write back into the file BUT my attempts have failed. Could someone lend me a hand, give me some tips, grant a miracle(make me perl omniscient :) ). thanks again for your time.

Replies are listed 'Best First'.
Re: please explain this script
by Abigail-II (Bishop) on May 28, 2004 at 13:38 UTC
    First of all, the program can be reduced in size:
    $/=\1;while(<>){$c=($c<<1)+($c>>31)+($.>>2==3?0:ord)}printf"%x",$c
    The program calculates a checksum, it does so by iterating over each character of the file ($/ = \1; while (<>)). It keeps a running, 32 bit checksum, initially zero. For each character, it will rotate the current checksum one bit leftward (note that it's rotating, not shifting). This is the ($c << 1) + ($c >> 31) part. Then for each fourth character, the code point number will be added to the running total. ($x >> 2 == 3 ? 0: ord); $x ++). Finally, the checksum is printed as a hex number.

    Note that it will display different sums depending whether you have a 32-bit or a 64-bit perl!

    Abigail

      Probably wouldn't be a bad idea to replace it with a md5 hash using Digest::MD5
      use Digest::MD5; my $hash = Digest::MD5->new(); $hash->addfile(*STDIN); print $hash->hexdigest()."\n";
      The resulting string is 4 times longer so its possible this would require adjustments elsewhere. You do however get the benefit of name recognition so anyone who comes across the code knows exactly what it is doing.
        the binary file actually stores the calulated checksum starting at the 12 byte and is expecting 32 bits. I was just wanting to know what the script was doing.
      one more question.. what is ord actually doing I thought ord makes asci characters. Please excuse my ignorance. and thanks for the help.
        ord returns the ordinal value (usually the ascii value) of a given literal character. For example, print ord('A'); prints 65.


        Dave