Input:
Some text here which may be any length and contain a number of child tags.
Expected output:
Some text here which may be any length and contain a quantity of child tags.
Code:
use XML::Twig;
my $file = ' Some text here which may be any length and contain a number of child tags.';
my $twig = new XML::Twig(TwigHandlers => {'paragraph' => \¶graph},TwigRoots => {paragraph => 1});
$twig->parse($file);
$twig->print;
sub paragraph {
my ($twig, $para,) = @_;
my $para_text = $para->text;
&choiceReplace($para,$para_text);
}
sub choiceReplace {
my ($para,$para_text) = @_;
my $search = "number"; #setting search and replace for example
my $replace = "quantity";
#locate each occurrence of search term and prompt user to replace
foreach ($para_text =~ /$search/) {
my $new_version = $para_text;
my $offset = 0;
my $new_offset = 0;
my $result = index($para_text, $search);
my $new_result = index($new_version, $search);
$offset = $result;
$new_offset = $new_result;
my $l = length ($search);
#loop through string search results while found
while (($result != -1) && ($new_result != -1)) {
#create visuals for user to accept/deny match
print "\n\nCurrent Version:\n $para_text";
my $replace_match = "**[[$replace]]**";
substr($new_version,$new_offset,$l) = $replace_match;
print "\n\nMatched Version:\n $new_version";
print "\nWould you like to make this change (y or n)? ";
chomp($change=);
if ($change eq "n"){
my $nm_result = rindex($new_version, $replace_match);
my $nm_l = length ($replace_match);
my $no_match = "[DENIED]";
substr($new_version,$nm_result,$nm_l) = $no_match;
}
elsif ($change eq "y") {
my $nm_result = rindex($new_version, $replace_match);
my $nm_l = length ($replace_match);
my $no_match = "[CHANGED]";
substr($new_version,$nm_result,$nm_l) = $no_match;
substr($para_text,$offset,$l) = $replace;
}
#update search starting point
$result = index($para_text, $search, $offset + 1);
$offset = $result;
$new_result = index($new_version, $search, $new_offset);
$new_offset = $new_result;
}
#set text for
@_[0]->set_text($para_text);
}
}