Jay
Jay

Reputation: 751

Is there a built-in perl function that determines length of numeric variable?

I am parsing a text file with the following format that needs to be distinguished.

cat       dog      [numeric, 00-23]
pickle    fence    [numeric, 0-5]
tack      glue     [numeric,1-53]
dent      paint    [numeric01-15]

If the minimum of the range is a single digit, then I need to process it a certain way. If the minimum of the range is double-digit (including 00,01,02,etc), I need to process it another way.

if($line =~ /\[numeric.*(\d+)\-(\d+)/i){
       $rangemin=$1;
       $rangemax=$2;
       #find # of digits in $rangemin
       #length() doesn't work
       #I'm trying to find a function that finds number of digits so length of `00` or `01` or `02` or etc. returns `2` 
}

How do I find the # of digits of $rangemin?

Upvotes: 1

Views: 220

Answers (2)

toolic
toolic

Reputation: 62237

Your regular expression grabs the leading 0 because .* is very greedy.

use warnings;
use strict;

while (my $line = <DATA>) {
    if ($line =~ /\[numeric[\D]*(\d+)\-(\d+)/i){
        my $rangemin = $1;
        my $len = length $rangemin;
        print "rangemin=$rangemin len=$len\n";
    }
}

__DATA__
cat       dog      [numeric, 00-23]
pickle    fence    [numeric, 0-5]
tack      glue     [numeric,1-53]
dent      paint    [numeric01-15]

Output:

rangemin=00 len=2
rangemin=0 len=1
rangemin=1 len=1
rangemin=01 len=2

Upvotes: 6

Hunter McMillen
Hunter McMillen

Reputation: 61540

You can use the length built-in, just like you would for a string; Perl implicitly converts arguments based on the operator/builtin that they are being passed to:

#!perl 

use strict; 
use warnings; 

my $number = 5; 
print length($number), "\n";

You can also use a base-10 logarithm to determine how long a number is:

#!perl 

use strict;
use warnings; 

my $number = 12345;
my $length = $number > 0 
    ? int(log($number)/log(10)) + 1
    : $number == 0 
          ? 0 
          : int(log(abs($number))/log(10)) + 2;
print $length, "\n"; 
# 5

**EDIT: as @Keith Thompson points out, log is not defined for numbers <= 0. Use abs to prevent this condition.

Upvotes: -1

Related Questions