Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

(Ovid) Re: Extract numbers in multiple bases

by Ovid (Cardinal)
on Oct 15, 2001 at 03:07 UTC ( [id://118787]=note: print w/replies, xml ) Need Help??


in reply to Extract numbers in multiple bases

My first pass at this seems to work okay, though I should probably add a few more tests. Though I have regexes to specify formats, I tried to make it fairly simple to maintain, in case specifications change. There's a test at the top of the code. Just add numbers you want to test to the array to see if they pass or fail.

#!/usr/bin/perl -w use strict; use Data::Dumper; my @nums = qw/ 0xff 09h 123.25 14E+12 0xfffa 0xffffh 123.25t 777o 123. +23.45 1.2e+13 /; foreach ( @nums ) { my $result = convert_num( $_ ); if ( $result->{ valid } ) { print "$_ is a $result->{base} number with a $result->{value} +decimal value.\n"; } else { print "$_ is not a valid number.\n"; } } sub convert_num { my $num = shift; my %bases = ( hex => { description => [ qw/ ^0x[A-Fa-f0-9]+$ ^[A-Fa-f0-9]+h$ / ], function => sub { ( $_[0] ) = ( $_[0] =~ /(?:0x)?([a-fA +-F0-9]+)/ ); hex( $_[0] ) } }, octal => { description => [ '^[0-7]+o$' ], function => sub { ( $_[0] ) = ( $_[0] =~ /([0-7]+)/ ); +oct( $_[0] ) } }, decimal => { description => [ qw/ ^\d*\.\d+(?!\.)\d*t?$ / ], function => sub { $_[0] =~ s/t$//; $_[0] } }, scientific => { description => [ '^\d*\.?\d+(?!\.)\d*[Ee]\+\d+$' ], function => sub { 1 * shift } } ); my %result = ( valid => 0, base => '', value => $num ) ; foreach my $base ( keys %bases ) { foreach my $regex ( @{ $bases{$base}{description} } ) { if ( $num =~ /$regex/ ) { $result{ valid }++; $result{ base } = $base; } } } if ( $result{ valid } != 1 ) { @result{ qw/ valid base value / } = ('','',''); } else { my $function = $bases{ $result{ base } }{ function }; $result{ value } = $function->( $num ); } return \%result; }

To be perfectly fair, the scientific notation regex is a bit of a hack and needs to be fixed.

The code works by checking whether the argument to the sub is valid for one of the regexes specified in the %bases hash. If it's valid for more than one type, then the argument is considered ambiguous.

Cheers,
Ovid

Update: Looking at MrNobo1024's code and it seems like I overcoded the heck out of this.

Vote for paco!

Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://118787]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (5)
As of 2024-03-28 20:34 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found