in reply to Parse float from string

Personally I'd use a regexp to do this. Something like:
sub parseInt { my $str = shift; $str =~ /(\d+)/; return $1; }
Michael

Replies are listed 'Best First'.
Re:x2 Parse float from string (use Regexp::Common)
by grinder (Bishop) on Nov 05, 2002 at 09:20 UTC

    If you're going to use a regexp to parse a number (which seems to me to be the right approach as well), the best bet would be to use Conway's Regexp::Common module (actually Regexp::Common::number but that link dumps you into a page of results) which does this for you (and one would assume that it gets all the hairy bits right).

    use Regexp::Common qw/number/; sub make_num { return $_[0] =~ /(^$RE{num}{real}$)/ ? $1 : undef; }

    tweaked: s/is_num/make_num/ and changed the return value, in order to be more in line with the original question.



    print@_{sort keys %_},$/if%_=split//,'= & *a?b:e\f/h^h!j+n,o@o;r$s-t%t#u'
Re: Re: Parse float from string
by samurai (Monk) on Nov 05, 2002 at 00:22 UTC
    Unfortunately, that won't catch the period character. I would use transliteration, IF you know what characters you should ignore.

    $string =~ y/A-Za-z //d;

    That'll remove alphabeticals and spaces. However, you may have to specify more characters if there's more garbage in your $string's.

    --
    perl: code of the samurai

      Sorry if I misread - the original poster had a parseInt() sub defined...
      To parse a float:
      sub parseFloat { my $str = shift; $str =~ /([\d\.]+)/; return $1; }
      Michael
        That is not going to work for: -11.10 11.10.11