Hello,
It's the "shift". In the sub, "shift" is grabbing an argument (the number
being passed in). Outside of the sub ... well, it's not doing what you
expect.
Looks like you want pack() to operate on the value of $str. So, try
substituting $str for that "shift", i.e.:
$str = unpack("B32", $pack("N", $str));
Have fun,
- Chris
-----Original Message-----
From: Hassan Eshtiaghi [Nick] [mailto:[EMAIL PROTECTED]]
Sent: Thursday, June 07, 2001 3:13 PM
To: [EMAIL PROTECTED]
Subject: Decimal To Binary
The following sub is in the Perl Cookbook, section 2.4.1(Converting Between
Binary and Decimal). When I call the sub I get the correct output, but if I
use the same unpack and pack functions as stand-alone statements, outside a
sub, the output is always 0(zero). What am missing?
sub dec2bin {
my $str = unpack("B32", pack("N", shift));
$str =~ s/^0+(?=\d)//; # otherwise you'll get leading zeros
return $str;
}
$binstr = dec2bin(54);
print $binstr # This gives me the right output.
-----------------------------------
Using the same concept outside the sub:
$str = 54;
$str = unpack("B32", $pack("N", shift));
$str =~ s/^0+(?=\d)//; # otherwise you'll get leading zeros
printf("%s \n", $str); #This gives me 0.