regexstringperlstring-substitution

Perl, How to find and modify multiple expressions in a single string


I have a file that contains many lines like the following:

some text { {{7.718 1072.463} {7.718 1230.985} {15.724 1230.985} {15.724 1198.742} {15.759 1198.742} } {{7.702 1072.489} {7.702 889.858} {13.418 889.858} {13.418 887.367} {13.435 887.367} {13.435 887.376} {7.144 887.376} } } some more text

Each pair of values are X and Y coordinates. For each line in the file, I want to find every X value and add a certain value (lets say 6.3) and print that new line. The X value will always follow a { without any space. I am able to get each X value in a single line with this while loop:

 while ($line=~/\{\d+(?:\.\d+)?/g) {
     $oldX=~s/\{//;
 }

But how can I add a value (like 6.3) to every X occurrence of X value I find the string? I want the new string to look just like the original except each X value should be increased by 6.3.

Thank you for any guidance on this.


Solution

  • $line =~ s/\{\K(\d+(?:\.\d+)?)/$1 + 6.3/ge will replace each number immediately following a curly bracket ({) with the same number increased by 6.3.

    The \K keeps the curly brace. The /e flag to s/// evaluates the expression in the replacement part of the substitution. And g flag replaces every occurrence of the match.

    If you need to match numbers that start with a dot (e.g. .25), try:

    $line =~ s/\{\K(\d+(?:\.\d+)?|\.\d+)/$1 + 6.3/ge
    

    You can replace 6.3 in the regex with the variable containing the amount to add.