D
debjyoti
Hi all
I was messing around with a perl script and realized converting
strings to integers/floats is iffy on perl (compared to C). There is
all this mention of atoi/atof being system dependent etc and so I
found this piece of code for atoi():
sub atoi {
my $t;
foreach my $d (split(//, shift())) {
$t = $t * 10 + $d;
}
return $t;
}
http://perl.plover.com/IAQ/IAQlist.html#how_do_i_convert_a_string_to_a_number
It worked for my applicaton and then I needed an atof(). It was easy
to enhance the above:
sub atof {
my $pre;
my $suf;
my $t;
$in = shift();
@dual = split(/\./,$in );
foreach my $d (split(//, $dual[0])) {
$pre = $pre * 10 + $d;
}
$div = 1;
foreach my $d (split(//, $dual[1])) {
$suf = $suf * 10 + $d;
$div *= 10;
}
$t = $pre + ($suf/$div);
#print "!!!debug!!! $in $dual[0] , $dual[1] [$pre + ($suf / $div) =
$t]\n";
return $t;
}
Putting it here incase it is useful to some perl newbie... and in case
I need it future
I was messing around with a perl script and realized converting
strings to integers/floats is iffy on perl (compared to C). There is
all this mention of atoi/atof being system dependent etc and so I
found this piece of code for atoi():
sub atoi {
my $t;
foreach my $d (split(//, shift())) {
$t = $t * 10 + $d;
}
return $t;
}
http://perl.plover.com/IAQ/IAQlist.html#how_do_i_convert_a_string_to_a_number
It worked for my applicaton and then I needed an atof(). It was easy
to enhance the above:
sub atof {
my $pre;
my $suf;
my $t;
$in = shift();
@dual = split(/\./,$in );
foreach my $d (split(//, $dual[0])) {
$pre = $pre * 10 + $d;
}
$div = 1;
foreach my $d (split(//, $dual[1])) {
$suf = $suf * 10 + $d;
$div *= 10;
}
$t = $pre + ($suf/$div);
#print "!!!debug!!! $in $dual[0] , $dual[1] [$pre + ($suf / $div) =
$t]\n";
return $t;
}
Putting it here incase it is useful to some perl newbie... and in case
I need it future