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

Hello, I've got file with strings with digital data. What is the simplest way to convert this data into a floats? This is an example of data lines:
360.000 -0.000100033 -1.76122e-05 -9.89111e-05 -1.9003e-05 640.000 -4.54467e-05 9.13758e-05 -4.50576e-05 9.04804e-05
Data::Str2Num - looks ok, but very old with some errors and I'm afraid not very reliable. Thank you

Replies are listed 'Best First'.
Re: How to read string with numbers
by Athanasius (Archbishop) on Jun 14, 2015 at 03:42 UTC

    Hello luxs,

    I don’t think you need a module for this task. Does the following meet your requirements?

    #! perl use strict; use warnings; use Data::Dump; while (my $line = <DATA>) { my @strings = split /\s+/, $line; my @floats = map { $_ + 0 } @strings; dd \@floats; } __DATA__ 360.000 -0.000100033 -1.76122e-05 -9.89111e-05 -1.9003e-05 640.000 -4.54467e-05 9.13758e-05 -4.50576e-05 9.04804e-05

    Output:

    13:40 >perl 1272_SoPW.pl [360, -0.000100033, -1.76122e-005, -9.89111e-005, -1.9003e-005] [640, -4.54467e-005, 9.13758e-005, -4.50576e-005, 9.04804e-005] 13:40 >

    Hope that helps,

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Re: How to read string with numbers
by trippledubs (Deacon) on Jun 14, 2015 at 03:57 UTC
    Using Scalar::Util::Numeric
    #!/usr/bin/env perl use strict; use warnings; use Scalar::Util::Numeric qw(isfloat); use Data::Dumper; my @data; push @data, grep { isfloat($_) } split /\s+/ while <DATA>; print Dumper @data; __DATA__ 360.000 -0.000100033 -1.76122e-05 -9.89111e-05 -1.9003e-05 640.000 -4.54467e-05 9.13758e-05 -4.50576e-05 9.04804e-05 123 V.1234
    dubs@server:~$ perl t1.pl $VAR1 = '360.000'; $VAR2 = '-0.000100033'; $VAR3 = '-1.76122e-05'; $VAR4 = '-9.89111e-05'; $VAR5 = '-1.9003e-05'; $VAR6 = '640.000'; $VAR7 = '-4.54467e-05'; $VAR8 = '9.13758e-05'; $VAR9 = '-4.50576e-05'; $VAR10 = '9.04804e-05';
Re: How to read string with numbers
by AnomalousMonk (Archbishop) on Jun 14, 2015 at 16:41 UTC

    The other question to ask is "What do I care?" Perl converts between numbers and strings based on operational context in a way that, in most cases, "does what you want":

    c:\@Work\Perl\monks>perl -wMstrict -MData::Dump -le "my $f = '360.000' + '-1.9003e-05'; dd $f; ;; my $s = 360.000 . -1.9003e-05; dd $s; " 359.999980997 "360-1.9003e-005"


    Give a man a fish:  <%-(-(-(-<

Re: How to read string with numbers
by shawnhcorey (Friar) on Jun 15, 2015 at 12:37 UTC
    Perl automatically converts text to number and back again. It does not make a distinction between integers and floats.
    #!/usr/bin/env perl use strict; use warnings; use Scalar::Util qw( looks_like_number ); while( <DATA> ){ my @numbers = map { $_ + 0 } grep { looks_like_number $_ } split; print "@numbers\n"; } __DATA__ 360.000 -0.000100033 -1.76122e-05 -9.89111e-05 -1.9003e-05 640.000 -4.54467e-05 9.13758e-05 -4.50576e-05 9.04804e-05