Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things

Re: multiplication a column of data in csv file by a factor

by Laurent_R (Canon)
on Apr 03, 2019 at 15:44 UTC ( #1232101=note: print w/replies, xml ) Need Help??

in reply to multiplication a column of data in csv file by a factor

Hi ng0177,

First please note that the sprintf builtin does not print out anything: it only returns a formatted string. In your code, the call to sprintf does not do anything useful, since you're not using the return value. You need to either use print to print out the string produced by sprintf, or use printf.

Second, it seems that you're using sort with the aim to modify the values in your array of arrays, rather than for sorting purposes. That's not really the right tool for that. Use a for loop or a map statement (depending on whether you want to modify your data structure in place or create a new data structure).

Perhaps that's more or less what you looking for:

use strict; use warnings; my @multi_array = map [split], <DATA>; my @by_second = map {$_->[1] *= 1.1E3; $_;} @multi_array; printf "%E %E %E\n", @{$_}[0..2] for @by_second; __DATA__ 1.10000E0 1.00000E0 1.00000E0 2.20000E0 2.00000E0 2.00000E0 3.30000E0 3.00000E0 3.00000E0
which produces the following output (which is presumably what you're looking for):
$ perl 1.100000E+00 1.100000E+03 1.000000E+00 2.200000E+00 2.200000E+03 2.000000E+00 3.300000E+00 3.300000E+03 3.000000E+00
If you insist on reducing the number of code lines, you could do it directly (without the auxiliary arrays) like this:
use strict; use warnings; printf "%E %E %E\n", @{$_}[0..2] for map {$_->[1] *= 1.1E3; $_;} map [ +split], <DATA>;
or possibly with only one map statement (but the code doesn't get shorter):
printf "%E %E %E\n", @{$_}[0..2] for map {my $c = [split]; $c->[1] *= +1.1E3; $c;} <DATA>;
I kept relatively close to your code to try to explain some of the problems in your script and show possible ways to solve them, but, as pointed out by choroba, using Text::CSV might be a good idea.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1232101]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (4)
As of 2020-09-26 00:07 GMT
Find Nodes?
    Voting Booth?
    If at first I donít succeed, I Ö

    Results (141 votes). Check out past polls.