Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

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

In reply to my $1 by mltucker

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others taking refuge in the Monastery: (2)
As of 2024-04-19 20:27 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found