Number Parsing in Perl

Parsing numbers from strings is a basic but common task in many programs; here’s how to do it in Perl.

use strict;
use warnings;

# Perl doesn't have a built-in package for number parsing like Go's strconv,
# but we can use the core modules and built-in functions for this purpose.

# With float parsing, we don't need to specify precision in Perl.
my $f = 1.234;
print "$f\n";

# For integer parsing, Perl automatically detects the base.
my $i = int("123");
print "$i\n";

# Perl recognizes hex-formatted numbers with the '0x' prefix.
my $d = hex("0x1c8");
print "$d\n";

# Perl doesn't distinguish between signed and unsigned integers in the same way as Go.
my $u = int("789");
print "$u\n";

# Perl's int() function is similar to Go's Atoi for basic base-10 int parsing.
my $k = int("135");
print "$k\n";

# To handle parsing errors, we can use eval.
my $result = eval { int("wat") };
if ($@) {
    print "Error: $@";
}

Let’s go through this code:

  1. In Perl, we don’t need a specific function to parse floats. The language automatically handles this conversion.

  2. For integer parsing, we use the int() function. It automatically detects the base of the number.

  3. Perl recognizes hexadecimal numbers prefixed with ‘0x’. We can use the hex() function to convert these to decimal.

  4. Perl doesn’t distinguish between signed and unsigned integers in the same way as some other languages. The int() function works for both.

  5. The int() function in Perl is similar to Go’s Atoi for basic base-10 integer parsing.

  6. To handle parsing errors, we can use eval. If the parsing fails, it will set the $@ variable with the error message.

When you run this program, you should see output similar to this:

1.234
123
456
789
135
Error: Argument "wat" isn't numeric in int at ...

Next, we’ll look at another common parsing task: URLs.