Zaserov has asked for the wisdom of the Perl Monks concerning the following question:

I wrote a short program to sort through a long output file for various things, but the data in there was in scientific notation. The format is 1.12345E+05, and may have a leading -. So I wrote up this small subroutine:
sub scicon { my @result; for my $i (0 .. $#_) { my $string_in = $_[$i]; $string_in =~ /(-?\d.\d+)E(.\d+)/; my ($const, $expon) = ($1, $2); $result[$i] = ($const * 10 ** $expon); } return @result; }
As I'm new to the language (and programming, really), and this gets used 3 or 4 times per line of a million+ line file, I was wondering if there's a better way or even a built-in command for this. Thanks.

Replies are listed 'Best First'.
Re: Conversion from Scientific Notation
by ikegami (Patriarch) on Jul 24, 2009 at 16:54 UTC
    You could just use it as is.
    $ perl -le'print "1.12345E+05" - 100000' 12345

    All your work is equivalent to adding zero to the arg.

    $ perl -le'print 0+"1.12345E+05"' 112345
Re: Conversion from Scientific Notation
by JavaFan (Canon) on Jul 24, 2009 at 16:48 UTC
    Perl has no problem understanding "1.12345E+05". That "looks like a number", so if you use it as a number, Perl will treat it as a number.
    print "1.12345E+05" + 100; # Prints 112445; no warnings.
Re: Conversion from Scientific Notation
by kennethk (Abbot) on Jul 24, 2009 at 16:49 UTC
    Probably my favorite thing about Perl (it is, at the least Waaay up there) is the scalar typing system. Read about it here: Perl variable types. In your case, it's great because you don't need to parse that expression - store the whole thing as a string, and Perl will automatically use it as a float whenever you want (i.e. when you use it in a numeric context).
Re: Conversion from Scientific Notation
by Zaserov (Novice) on Jul 24, 2009 at 17:04 UTC
    Right, that makes sense. Now that I think about it, when I tried to use the wrong regex to get the numbers out, I somehow assumed that my mistake meant that perl was lacking the ability to deal with the numbers. So I wrote this without even trying the strings. Thanks all for the responses!