http://www.perlmonks.org?node_id=759641
mltucker has asked for the wisdom of the Perl Monks concerning the following question:

Hi,

I'm working on my first Perl program, and I ran into an issue. The goal is simple, pattern matching symbolic differentiation. It doesn't need to do recursive descent or anything.

The way I'm implementing it is with a recursive call to a "diff" subroutine. Here's part of my code to illustrate my problem:

#!/usr/bin/perl print diff(shift)."\n"; sub diff { my $_ = shift; # I make this local since I'll be making # recursive calls # I'll just include addition: return diff($1)."+".diff($2) if m/(.+?)\+(.+); ... # other differentiation rules here }

Here's the problem: when I recursively call diff using $1 as the argument, it will potentially do more captures and change the value of $2 by the time it gets back to do the second recursive call in the original addition. The easy fix is to name the variables under local scope:

... if (m/(.+?)\+(.+)) my $firstTerm = $1; my $secondTerm = $2; return diff($firstTerm)."+".diff($secondTerm);

But since this would come up for all of the differentiation rules, my idea was to have local copies of the captured strings on each frame of the stack (the same way I have $_):

sub diff { my $_=shift; my $1; my $2; ... }

But then I get the error:

Can't use global $1 in "my"... Execution ... aborted due to compilation errors.

Is there any way I can get it to work like this? Why do $1 and $2 behave differently than $_ in this case? Isn't $_ also "global"?

Thanks!

-Mark