While this is probably strictly true, Perl is all about letting you get the job done:
my $str = "eeeeaaaabbbeeee"; $str =~ s/((a+)(??{'b'x length$2}))/'c' x (length($1) * .5) . 'd' x (l +ength($1) * .5)/e;
Anyhoo...I have just recently started learning Parse::RecDescent. Update: I am not sure if this is what you had in mind, but the following accomplishes what you want without using sneaky experimental regex features.
A lot of this code could be simplified and improved. I am neither a regex nor Parse::RecDescent guru. I did show how either could work.#!/usr/bin/perl use strict; use warnings; use Parse::RecDescent; $Parse::RecDescent::skip = ''; my $grammar = q{ match : PREFIX TOKEN SUFFIX {print join '', @item[1..3]} PREFIX : /.*?(?=a+b+)/ TOKEN : /a+b+/ { my $str = $item[1]; my $a_cnt = $str =~ tr/a//; my $b_cnt = $str =~ tr/b//; if ($a_cnt == $b_cnt) { $return = ('c' x $a_cnt) . ('d' x $b_cnt); } elsif ($a_cnt > $b_cnt) { $return = ('a' x ($a_cnt - $b_cnt)) . ('c' x $b_c +nt) . ('d' x $b_cnt); } else { $return = ('c' x $a_cnt) . ('d' x $a_cnt) . ('b' +x ($b_cnt - $a_cnt)); } } SUFFIX : /.*$/ }; my $parser = Parse::RecDescent->new($grammar); $parser->match('sing aaaaaabbb song');
Once you have a string of a's followed by one or more b's ($item[1]), you only needed to calculate the desired string and assign it to $return. An explicit assignment to $return is not necessary as you could just let the last expression be returned as with Perl's subroutines.
Cheers - L~R
In reply to Re: Parse::RecDescent for simple syntax-directed translation
by Limbic~Region
in thread Parse::RecDescent for simple syntax-directed translation
by tomazos
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |