in reply to How to search and replace text characters in a perl script

Here's one example, kind of following along the code layout you already have. In the 'E' case, we simply attempt a regex substitution (s//;), and for the 'Z' entries, we check if we have a match first, capture the match into two parts ($1, $2), and if there is a match, we do the substitution:

while (<>) { chomp; # EN.NNNNN # no need for if(), we're not using the capture number vars s/E\d\.\d{5}//; # ZNN.NNN # need if, or it'll warn on no match if (/G1 Z\d{1,2}\.\d{3}/){ s/(G1 Z)(\d{1,2}\.\d{3})/$1-$2/; } print "$_\n"; }

Replies are listed 'Best First'.
Re^2: How to search and replace text characters in a perl script
by AnomalousMonk (Archbishop) on May 20, 2016 at 06:11 UTC
    # need if, or it'll warn on no match

    No need: no substitution is done, no capture variables are referenced, if no replacement match exists:

    c:\@Work\Perl\monks>perl -wMstrict -le "for my $s ('G1 Z0.050 F7800.000', 'G10 ; retract',) { printf qq{'$s' -> }; local $_ = $s; s/(G1 Z)(\d{1,2}\.\d{3})/$1-$2/; print qq{'$_'}; } " 'G1 Z0.050 F7800.000' -> 'G1 Z-0.050 F7800.000' 'G10 ; retract' -> 'G10 ; retract'
    (Although I think I would prefer to use look-arounds as graff did and just stick a - in.)


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

Re^2: How to search and replace text characters in a perl script
by thetekguy (Initiate) on May 20, 2016 at 03:14 UTC
    Beautiful! Thanks for the quick response. It would have taken me weeks of trial and error to get to this point- but this helps me learn for next time. Much appreciated! Here is the final working code:
    #!/usr/bin/perl -i.before_postproc # Author : David Sherwood # Version : 1.0 # Copyright : none. # # Postprocessor for Slic3R Gcode for Laser Cutter use strict; use warnings; # read stdin and any/all files passed as parameters one line at a time while (<>) { chomp; # EN.NNNNN # no need for if(), we're not using the capture number vars s/E\d\.\d{5}//; # ZNN.NNN # need if, or it'll warn on no match if (/G1 Z\d{1,2}\.\d{3}/){ s/(G1 Z)(\d{1,2}\.\d{3})/$1-$2/; } if (/G11/) { # if we have an un-retraction line, replace it with laser powe +r on print "M400 ; wait for moves to finish\nM104 S100 ; laser on\n +"; } elsif (/G10/) { # if we found a retraction line, replace it with laser power o +ff print "M104 S0 ; laser off\n"; } elsif (/G92/) { # if we found an extruder reset command line, remove it print ""; } elsif (/M190/) { # if we found a heat bed command line, remove it print ""; } else { print "$_\n" or die $!; } }