Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arithmetic Calculation in Perl Substitute Pattern Matching

Tags:

regex

perl

Using just one Perl substitute regular expression statement (s///), how can we write below:

Every success match contains just a string of Alphabetic characters A..Z. We need to substitute the match string with a substitution that will be the sum of character index (in alphabetical order) of every character in the match string.

Note: For A, character index would be 1, for B, 2 ... and for Z would be 26.

Please see example below:

success match: ABCDMNA  
substitution result: 38  

Note:

1 + 2 + 3 + 4 + 13 + 14 + 1 = 38; 

since

A = 1, B = 2, C = 3, D = 4, M = 13, N = 14 and A = 1.
like image 810
mike nomax Avatar asked Dec 04 '22 05:12

mike nomax


2 Answers

I will post this as an answer, I guess, though the credit for coming up with the idea should go to abiessu for the idea presented in his answer.

perl -ple'1 while s/(\d*)([A-Z])/$1+ord($2)-64/e' 

Since this is clearly homework and/or of academic interest, I will post the explanation in spoiler tags.

- We match an optional number (\d*), followed by a letter ([A-Z]). The number is the running sum, and the letter is what we need to add to the sum.
- By using the /e modifier, we can do the math, which is add the captured number to the ord() value of the captured letter, minus 64. The sum is returned and inserted instead of the number and the letter.
- We use a while loop to rinse and repeat until all letters have been replaced, and all that is left is a number. We use a while loop instead of the /g modifier to reset the match to the start of the string.

like image 102
TLP Avatar answered Dec 31 '22 01:12

TLP


Just split, translate, and sum:

use strict;
use warnings;

use List::Util qw(sum);

my $string = 'ABCDMNA';

my $sum = sum map {ord($_) - ord('A') + 1} split //, $string;

print $sum, "\n";

Outputs:

38
like image 24
Miller Avatar answered Dec 31 '22 03:12

Miller