Warm tip: This article is reproduced from serverfault.com, please click

Converting a string to float in Perl

发布于 2020-11-28 05:26:27

I'm new to Perl. I am reading a CSV file using Perl. The first column of the CSV is time (which is a float). I've read the CSV and displayed the contents of the CSV successfully. Further, I wish to use the CSV data for some computations. I need the time column as an array (or any data structure). On reading the time column and storing it in an array, it is stored as a string. I wish to have a numeric array for arithmetic computations.

I've tried adding 0, mul 1 and then storing it in the array,using sprintf but i'm encountering errors.

use v5.30.0;
use strict;
use warnings;

my $file = $ARGV[0] or die;
open(my $data, '<',$file) or die;
my @timeArray;

while(my $line = <$data>){
    chomp $line;
    my @words = split ",",$line;
    #my $temp=$words[1]*1;
    my $temp=sprintf "%.6f",$words[1];
    push @timeArray,$temp;
}

Error:

Argument ""67.891947295"" isn't numeric in multiplication (*) at 3.pl line 12, <$data> line 19556.

and 

Argument ""67.840034174"" isn't numeric in sprintf at 3.pl line 13, <$data> line 19555.

Also, why is the argument in "" "" .

Questioner
time_remnant
Viewed
0
Miguel Prz 2020-11-28 15:37:08

It's a good idea to handle data like that with the proper module, because there are several important details that you didn't take care of. Examples:

  • The columns values may be enclosed in quotes
  • The first row may contain the header names of each column
  • The last record in the file may or may not have an ending line break
  • Etc.

Read the RFC-4180 document for more information.

There are lots of modules that can parse CSV format, for example: Text:CSV. It's very easy to install, and when you use it, your string to double problem will disappear.