After playing a bit with perl 5.10 regexps I have being able to work a primitive infix to postfix translator with them:
Minus and divide operators seem to behave according the expected left associativity:pl@nereida:~/Lperltesting$ cat ./calc510withactions2.pl #!/usr/local/lib/perl/5.10.1/bin//perl5.10.1 use v5.10; # Infix to postfix translator using 5.10 regexp # Original grammar: # exp -> exp [-+] term # | term # term -> term [*/] digits # | digits # Applying left-recursion elimination we have: # exp -> term re # re -> [+-] term re # | # empty # term -> digits rt # rt -> [*/] rt # | # empty my @stack; my $regexp = qr{ (?&exp) (?(DEFINE) (?<exp> (?&term) (?&re) ) (?<re> \s* ([+-]) (?&term) \s* (?{ push @stack, $^N }) (?& +re) | # empty ) (?<term> (?&digits) (?&rt) ) (?<rt> \s*([*/]) (?&digits) \s* (?{ push @stack, $^N }) (? +&rt) | # empty ) (?<digits> \s* (\d+) (?{ push @stack, $^N }) ) ) }xms; my $input = <>; chomp($input); if ($input =~ $regexp) { say "matches: $&\nStack=(@stack)"; } else { say "does not match"; }
I feel however that I can't extend this methodology to more complex tasks because I haven't found a way other than $^N to refer to the values associated with the previous parenthesis. Which means that I can only refer to the attribute of the last parenthesis.pl@nereida:~/Lperltesting$ ./calc510withactions2.pl 2-8*4/2/4-1 matches: 2-8*4/2/4-1 Stack=(2 8 4 * 2 / 4 / - 1 -)
Is in Perl 5.10 something like relative variable backreferences so that I can use something like $-1, $-2, etc. to refer to the last parenthesis, the one before the last, etc. inside the embeded code? I.e. I am looking for s.t. similar to relative backreferences like \g{-1} but to be used inside inserted code?
Apologies for not being able to clarify the question enough. I feel I do not have yet a clear understanding of Perl 5.10 regexps.
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |