Your skill will accomplishwhat the force of many cannot PerlMonks

### Re: Scoped Variables in a Recursive Function.

by japhy (Canon)
 on Sep 28, 2000 at 16:46 UTC ( #34369=note: print w/replies, xml ) Need Help??

in reply to Scoped Variables in a Recursive Function.

You should not define a function inside a function. It does not behave as you'd expect. Instead, change your scoping slightly:
```{
my @array;
sub Merge {
@array = @_;
MergeSort(0, \$#array);
}
sub MergeSort {
# can see @array here...
}
}

\$_="goto+F.print+chop;\n=yhpaj";F1:eval

Replies are listed 'Best First'.
RE: Re: Scoped Variables in a Recursive Function.
by Adam (Vicar) on Sep 28, 2000 at 19:46 UTC
That will work, but as tilly pointed out, the problem is with the MergeSort code being named. This aught to work with the fewest changes to your code:
```sub Merge(@) {
my @array = @_;

local \$MergeSort = sub { ### Anonymous code ref. ###
my \$first = shift;
my \$last = shift;
if (\$last>\$first) {
my \$mid = int((\$last+\$first)/2);
\$MergeSort->(\$first, \$mid);
\$MergeSort->(\$mid+1, \$last);
my @b;

@b = ( @array[\$first..\$mid], @array[reverse(\$mid+1..\$last)] );
my (\$i, \$j, \$k) = (0, \$last-\$first, \$first);
for (; \$k<=\$last; \$k++) {
\$array[\$k] = (\$b[\$i]<\$b[\$j]) ? \$b[\$i++] : \$b[\$j--];
}
}
}

\$MergeSort->(0, \$#array);
return @array;

}
That ought to work, but it's silly, since it creates a code reference EVERY TIME you run Merge(). There's no reason to use a code reference. Define Merge() and MergeSort() in the same block, and have @array be shared between them.

\$_="goto+F.print+chop;\n=yhpaj";F1:eval
Yeah, I was thinking about that... I think you are right.

Create A New User
Node Status?
node history
Node Type: note [id://34369]
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (5)
As of 2017-06-28 15:14 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
How many monitors do you use while coding?

Results (640 votes). Check out past polls.