Since the examples of the programs that you indicated do not actually do anything, itโs difficult for you to give a specific reason why one type of declaration will be better than another. As noted by many other posters, declaring a variable in a loop creates a new variable each time. In your examples, that creation is redundant, but consider the following examples using closure.
my @closures; my $jimmy; for (1 .. 10) { $jimmy = $_** 2; push @closures, sub {print "$jimmy\n"}; }
and this one:
my @closures; for (1 .. 10) { my $jimmy = $_** 2; push @closures, sub {print "$jimmy\n"}; }
In each case, the code creates a series of links to the code, but in the first example, since all links to the code refer to the same $jimmy , each of them will print 100 when called. In the second example, each ref code will print a different number (1, 4, 9, 16, 25, ...)
So, in this case, the time difference does not matter much, since the two blocks of code have different things.
Eric Strom
source share