Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: How to strip non-numeric values from string?

by kennethk (Abbot)
on Mar 19, 2010 at 20:12 UTC ( [id://829694]=note: print w/replies, xml ) Need Help??


in reply to How to strip non-numeric values from string?

Number means a lot of things to a lot of people. One generally tricky bit to consider is scientific notation, i.e. "1.0e1". Fortunately, Perl is smarter than your average third-grader. If the unnecessary bit is only at the end of your string, you can simply use 0+ (the venus operator I think) to numify the result, and let Perl do the heavy lifting:

my @array = (" 321abc ", "100%", "20 lbs."); no warnings "numeric"; print(0+$_,"\n") for @array;

If you have leading chaff, you can run it through a substitution to strip that first:

my @array = (" 321abc ", "100%", "20 lbs.", "words20", "**39.99.99** +"); no warnings "numeric"; for (@array) { s/^[^0-9.-]+//; print(0+$_,"\n"); }

Replies are listed 'Best First'.
Re^2: How to strip non-numeric values from string?
by murugaperumal (Sexton) on Mar 20, 2010 at 04:20 UTC
    use strict; use warnings; for (qw(12.34 0.05lb 999)) { if($_=~/([0-9.]+)/) { print "$1\n"; } }

Log In?
Username:
Password:

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

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

    No recent polls found