Date: 2009nov26
Update: 2025oct22
Language: perl
Q. perl: How to convert a text (ASCII) string to an integer?
A. This does the trick:
$text = '123';
$n = $text + 0;
But you should check that $text is a valid number. Attempts to turn
non-numbers (eg 'hello') into numbers gives you 0. This function gives
undef for non-numbers.
sub asciiToInt($) {
my($text) = @_;
my($n);
if ($text =~ m/^\d+$/) {
$n = $text + 0;
}
return $n;
}
There is also hex() and oct() for converting base 16 and 8 numbers strings
into numbers.