in reply to Garbage collection at subroutine return

Since the subject of globals and scoping has come up I though I would point out a possible scoping issue with the $i variable in your code and liverpole's response. The $i inside the foreach loop is not the same one that you declared with the my $i; outside of it. The following code illustrates this.

use strict; use warnings; my $limit = 5; printLimit($limit); sub printLimit { my $limit = shift; my $i = q{xyz}; print qq{outside foreach: $i\n}; foreach $i ( 1 .. $limit ) { print qq{ inside foreach: $i\n}; } print qq{outside foreach: $i\n}; }

Here's the output

outside foreach: xyz inside foreach: 1 inside foreach: 2 inside foreach: 3 inside foreach: 4 inside foreach: 5 outside foreach: xyz

You have to introduce $i with a my somewhere since we are running with use strict; so, since it is only being used inside the loop, why not declare it there?

foreach my $i ( ... ) { ... }

I hope this is of interest.

Cheers,

JohnGG