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"; } }