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.