Perl help!! (pack()?)

Hello everyone.

I wrote a perl script to get the two answers from a value: x.
By this, I want to do sqrt($x) in different precision.

#!/usr/bin/perl

print "Input the initial value x:\n";
chomp($x=<STDIN>);
$comp=sqrt($x);
$float_value=pack("f", $comp);
$double_value=pack("d", $comp);
print "The answer by flaot is $float_value.\n";
print "The answer by double is $double_value.\n";
exit;

I don't know how to use "pack" function.
Please tell me.

No, you don't use pack() to do it. It packs the number in a binary representation that is never portable. And it's not printable.

Just use sprintf() and it should be fine. You can cast it to arbitrary precision as needed (provided that is supported):

D:\Documents and Settings\bernardchan>perl -e "print sqrt(5);"
2.23606797749979
D:\Documents and Settings\bernardchan>perl -e "print sprintf('%f', sqrt(5));"
2.236068
D:\Documents and Settings\bernardchan>perl -e "print sprintf('%.3f', sqrt(5));"
2.236

I can use printf() directly - just to show you that sprintf() returns a string representation that can be assigned to a scalar variable for later printing, storage or other processing.

Thank you very much, cbkihong.
I understood a lot.