http://www.perlmonks.org?node_id=230349


in reply to Cleaning Data Between Specified Columns

Taking one of the suggestions above, keeping your program flow intact, and mixing it a bit with my personal style, I come up with this:

#!/usr/bin/perl use strict; use warnings; # Store the ranges in a list of hashes. my @Ranges = (); foreach my $arg (@ARGV) { my ($start, $end) = split(/-/, $arg); push @Ranges, { start => $start, end => $end }; } # Use standard input/output so we can pipe files through it. while (my $line = <STDIN>) { # We go through the columns in reverse so the offsets will be # correct. foreach my $range (reverse @Ranges) { my ($start, $end) = ($range->{start}, $range->{end}); my $line_len = length($line); $end = $line_len if $line_len < $end; next if $start > $end; # Skip out-of-bound ranges my $nchars = $end - $start; substr($line, $start-1, $end-$start) = cleanse(substr($line, $start-1, $end-$start)); } print $line; } # Remove apostrophes and other unwanted characters. sub cleanse { my $string = shift; $string =~ s/'//g; $string =~ tr/a-zA-Z0-9\n\|\-/ /c; return $string; }

It could use some extra checking on the program arguments (ranges), though.

Arjen