Why does this line return sum of integers 1-10?

Viewed 85

I'd like to understand how unpack is returning the sum in the given perl one-liner.

I've looked at pack man page and mostly understood that it is simply formatting the given array into a scalar of ten doubles.

However, I couldn't find proper documentation for unpack with %123. Looking for help here.

print unpack "%123d*" , pack( "d*", (1..10));

This line correctly outputs 55 which is 1+2+3+...+10.

1 Answers

From perldoc -f unpack:

In addition to fields allowed in pack(), you may prefix a field with a % to indicate that you want a <number>-bit checksum of the items instead of the items themselves.

Thus %123d* means to add all the input integers 1..10 and then take the first 123 bit of this result in order to construct the "<number>-bit checksum". Note that %8d* or just %d* (which is equivalent to %16d*) would suffice too given that the sum is small enough.

Related