开发者

explain the following Perl Code?

Can anybody explain the following Perl code for me, please? I think its in Perl and I have no clue about Perl programmin开发者_开发问答g. Please explain what the following code does?

$t = test(10);
sub test() {
  my $str = unpack("B32", pack("N",shift));
  $str2 = substr($str,16,length($str));
  return $str2;
}


The pack, unpack and substr functions are documented here, here and here, respectively.

pack("N"...) packs a number into a four-byte network-order representation. unpack("B32"...) unpacks this packed number as a string of bits (zeros and ones). The substr call takes the second half of this bit string (from bit 16 onwards), which represents the lower 16 bits of the original 32-bit number.

Why it does it this way is a mystery to me. A simpler and faster solution is to deal with the lower 16 bits at the outset (note the lower case "n"):

sub test($) {
  return unpack("B16", pack("n",shift));
}


shift

pops the first argument to the function from the list of arguments passed

pack("N", shift)

returns a 32bit network byte order representation of that value

my $str = unpack("B32", pack("N", shift));

stores a bitstring representation (32 bits worth) of said value (i.e. a string that looks like "00010011").

The substr is buggy and should be substr($str, 16); to get the last 16 characters of the above. (or substr($str, 16, 16);.)


In addition to Marcelo's answer, the shift function takes the @_ as its default argument. @_ contains the subroutine's arguments.


pack("N", shift) takes the argument of the function (return value of shift, which works on the arguments array by default) and makes it into an integer. The unpack("B32, part then makes it into string again, of 32 bits, so a string of 0's and 1's. The substr just takes the last 16 bit-characters, in this case.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜