I used Perl for years, but it has been a few years since. I would like some guidance, please. The task is simple. Make changes to a file based on Regex user input, and report how many changes were made. I have the basic changes working for a string passed in but wish to be able to pass in 2 RegEx containing Pattern and Replacement or one containing both. Maybe to change { to ( or to add or remove some chars.
use strict;
use warnings;
# Get file to process
(my $file, my $pattern, my $replacement) = @ARGV;
my $Count = 0;
# Read file
open my $FH, "<", $file or die "Unable to open $file for read exited $
+? $!";
chomp (my @lines = <$FH>);
close $FH;
# Parse and replace text in same file
open $FH, ">", $file or die "Unable to open $file for write exited $?
+$!";
for (@lines){
say {$FH} $_ unless (/$pattern/); #Write to file unchanged
say {$FH} $_ if (s/$pattern/$replacement/g); #Write to file change
+d
if ($_ =~ /$pattern/) { #Need to check & count multiple occur
+rences in same line
$Count = $Count + 1; #Need to increment correctly
print $Count; #Wanted to test but will not print
return $Count; #Need to get count back to main
}
}
close $FH;
print $Count;
#Should have total count of changes for file
Thanx much for your time, and any help given. Bob
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.