Forgive me for the (probably) stupid question, but I’m messing around with this code (actually a model of something in a larger program), and something is throwing me off:
sub recurse {
my $m = shift;
$g .= "::" . $m;
if ($m == 0) { return $g; }
else { $m--; recurse ($m); }
}
for ($i = 0; $i < 3; $i++)
{
my $g = '';
$str = recurse (10);
print $str . "\n";
}
The first iteration of the ‘for’ loop works fine. On subsequent iterations, however, I am having an issue. As you can see, the global variable $g is reset first thing in the ‘for’ loop before the recursive function is called. With the debugger, I can see that $g is set back to ” before the function is called. However, as soon as the function ‘recurse’ is entered, it goes back to the previous value. What am I missing here?
As a corollary, I don’t like using a global variable here. What is the ‘correct’ way to do it without making $g a parameter for recurse()?
my $gis a local variable so it’s not the same one you use insiderecurse. Removingmywill fix that, though it’s still going to be an ugly code.You can pass
$ga second parameter to theresursefunction.Note:
use strict;is your friend 😉