Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re: How to search and replace text characters in a perl script

by graff (Chancellor)
on May 20, 2016 at 02:56 UTC ( #1163572=note: print w/replies, xml ) Need Help??


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

First, a couple nitpicks:
  • You have a comment saying "read stdin and any/all files passed as parameters..." Actually, it should say "or" instead of "and" -- the while(<>) reads either from file names given on the command line, or from STDIN, not both.
  • If you think you need to do print or die $! at all, you should do it on every print statement. (But you probably don't need to do it at all. When a print to STDOUT fails, you either don't need to be told, or else you'll get other error messages anyway.)
  • Doing print "" is a noisy way of doing nothing at all.

All that aside, I think the device you're looking for is the "look-around" assertions in a regex. Here's a slightly modified version of your code (because sometimes I can't help but change things), with the relevant bits added in the final "else" block:

#!/usr/bin/perl use strict; use warnings; my @G1x_replace = ( "M104 S0 ; laser off\n", "M400 ; wait for moves to finish\nM104 S100 ; laser on\n", ); while (<DATA>) { if ( /G1([01])/ ) { print $G1x_replace[ $1 ]; } elsif ( /G92|M190/ ) { next; } else { s/(?<=G1 Z)(?=\d)/-/g; # look-behind and look-ahead to insert + "-" s/E[\d.]+ //g; # no look-around needed, just delete s +tuff print; } } __DATA__ G92 E0 ; want to remove all G92 lines (works now) T1 G1 Z0.050 F7800.000 G10 ; retract G92 E0 G1 Z0.150 F7800.000 G1 X14.725 Y-8.975 F7800.000 G1 Z0.050 F7800.000 G11 ; unretract G92 E0 G1 X14.725 Y8.975 E0.01465 F120.000 G10 ; retract G92 E0 G1 Z0.150 F7800.000 G1 X-9.585 Y-0.615 F7800.000 G1 Z0.050 F7800.000 G11 ; unretract G92 E0

Replies are listed 'Best First'.
Re^2: How to search and replace text characters in a perl script
by thetekguy (Initiate) on May 20, 2016 at 03:20 UTC
    Perl is such a powerful language there are many ways to skin a cat. I use a blunt knife, most of you use a scalpel. :-) I am reading all responses and will learn from them all. Thanks gurus!

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (2)
As of 2021-02-26 16:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?