Hello, Perl monks!
A new user here, who is not a programmer really (so be gentle).
I am trying to write some code to round floating-point numbers with four decimal places to a nearest value with three decimal places. The input file contains G-code for CNC with many X, Y, and Z coordinates that have to be rounded. The problem with G-code is that different CAM programs format it differently (some separate values with white spaces, and some don't), so the Perl script has to be flexible. Here is an example of possible CNC code:
G00 G49 G40.1 G17 G80 G50 G90 G21 (4th Axis Parallel Finishing) M6 T2 M03 S18000 G01 X0.0000 Y19.0000 Z62.5685 A0.000 F2700. Z21.6142 A0.000 Y24.5818 Z19.2053 A0.000 F3000. Y30.1636 Z16.6406 A0.000 Y33.8516 Z14.8289 A0.000 Y36.9415 Z13.1956 A0.000 Y39.3337 Z11.8378 A0.000 Y40.9783 Z10.8384 A0.000 Z16.5551 A-0.296 Y32.5072 Z15.5003 A-360.000 Y28.9189 Z17.2258 A-360.000 Y23.7358 Z19.5824 A-360.000 Y19.0000 Z21.6142 A-360.000 Z62.5685 A-360.000 M5 M9 M30
It might as well look like this:
G00G49G40.1G17G80G50G90 G21 (4th Axis Parallel Finishing) M6T2 M03S18000 G01X+0.0000Y+19.0000Z+62.5685A0.000F2700. Z21.6142A+0.000 Y+24.5818Z+19.2053A+0.000F3000. Y+30.1636Z+16.6406A+0.000 Y+33.8516Z+14.8289A+0.000 Y+36.9415Z+13.1956A+0.000 Y+39.3337Z+11.8378A+0.000 Y+40.9783Z+10.8384A+0.000 Z+16.5551A-0.296 Y+32.5072Z+15.5003A-360.000 Y+28.9189Z+17.2258A-360.000 Y+23.7358Z+19.5824A-360.000 Y+19.0000Z+21.6142A-360.000 Z+62.5685A-360.000 M5M9 M30
(or something in between.)
I am interested only in X, Y, Z, and possibly A coordinates, and the rest to stay untouched.
Here what I came up with so far (consider it a pseudo-code):
open FILE, "<", $ARGV[0] or die $!; while(<FILE>) { chomp(); while (/\G.+/g) { # iterate throug the line if (/([XYZA])([+-]?\d+\.\d+)/) { # if matches a co +ordinate my $coord = sprintf("<$1%.3f>", $2); # round the value, print "$coord"; # and print it } else { # trouble! print; # I'd like to print n +on-matching cases } print "\n"; # finish printing + the line } }
Thank you very much for your time, and pardon me my English.
In reply to Rounding numbers in a string by fauve
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |