in reply to Trying to streamline repetitive code....
In a recent node (Re: Uploading pictures - displays only 2 of 12) I helped someone factor a chunk of code with the same problem.
In the end, I would like this one section of code to be able to sweep through M1, M2, M3, M4, M5, M6, M7, and M8, but I really don't want to put a variable name in a variable name because, well, according to other postings that would make me an idiot.
You're obviously not an idiot, as you know enough to ask the question! Using a hash is the better way to change the variable you use between iterations of code. It's a little tricky to fix it in one shot, so first run your program to get a "reference output" and save the output to a file. Then, after making each change, you can verify that the code still works by running again with the same parameters and checking the output with diff.
I think the first thing you want is to figure out what variable you want to use to sweep through your M1..M8 variables. For this post, I'm going to use $Mx. Then I'd change all variable names in the form $M8foo to $foo{$Mx} and declare the appropriate hashes, e.g. %foo. Do the same thing for the arrays & such. Assuming you're using warnings and strict, you can then fix the syntax errors that crop up. Once you get that section working, you can comment out the M1..M7 chunks, and surround the former M8 section with:
for $Mx qw(M1 M2 M3 M4 M5 M6 M7 M8) { ... $PinName{$Mx} = ...; $LayerName{$Mx} = ...; ... }
There are further simplifications you can make. Most (all?) of the variables containing M8 could be subkeys of a common hash, say %Tracks (or whatever name would have the most meaning in your application). Thus $M8PinName becomes $Tracks{$Mx}{PinName}, $NewM8UY becomes $Tracks{$Mx}{NewUY}, etc.
After doing that, then you'll find that $Tracks{$Mx} could be a bit repetitious, so you could modify your outer loop to something like:
for $Mx qw(M1 M2 M3 M4 M5 M6 M7 M8) { my $cur = $Tracks{$Mx}; ... $$cur{PinName} = ...; $$cur{LayerName} = ...; ... }
Take it a bit at a time, and it should clean up nicely. Let us know what you simplify it to, and we can make further suggestions.
...roboticus
|
|---|