Reputation: 242
In a text file, I have many lines looking like (a,b,c)
where a, b, and c are double precision real numbers, for instance (8.27605704077856,0.505526531790625,1.15577754382534e-05)
. Is there a simple way to replace numbers smaller than 10e-4 by 0 in Perl?
Edit: For instance, the text file to be treated looks like:
\plotinstruction[color,style,width]
points{
(8.27,0.5,1.1e-05)
(8.26,1,4.1e-06)
(8.25,1.5,3e-06)
}
and I want to write in a new file:
\plotinstruction[color,style,width]
points{
(8.27,0.5,0)
(8.26,1,0)
(8.25,1.5,0)
}
Upvotes: 0
Views: 222
Reputation: 183456
You can write:
perl -pwe 's/\d[\d.e+-]+/$& < 0.001 && $& > -0.001 ? "0" : $&/ge' < INPUT > OUTPUT
(-p
means to read in the input, one line at a time, into $_
, run the program, print out $_
, and loop again; -w
enables warnings; -e
means that the program is specified directly as a command-line argument; s///
is a regex-substitution; /g
means that it's a "global" substitution; and /e
means that the replacement-text should be treated as a full Perl expression, rather than as a string with mere variable interpolation.)
Upvotes: 0
Reputation: 96966
Perhaps I'm missing something, but perhaps use of map
would help?
#!/usr/bin/env perl
use strict;
use warnings;
use Data::Dumper;
my @values = (8.27605704077856, 0.505526531790625, 1.15577754382534e-05);
my @filtered_values = map(($_ > 1e-4) ? $_ : 0, @values);
print Dumper \@filtered_values;
Results:
$VAR1 = [
'8.27605704077856',
'0.505526531790625',
0
];
To parse input, you could use a regular expression to extract a comma-separated string of numbers, using split
on that to get a Perl list to run map
upon.
Upvotes: 3