Hello gauss76,
Since you are asking on how to improve your code. One possible way could be also making it faster:
#! /usr/bin/perl use strict; use warnings; use feature 'say'; # use Benchmark qw(:all) ; # WindowsOS use Benchmark::Forking qw( timethese cmpthese ); # UnixOS sub for_loop { for my $iloop (0 .. 10){ say $iloop; } return; } sub while_loop { my @numbers = qw( 1 2 3 4 5 6 7 8 9 10 ); while (defined(my $int = shift @numbers)) { say $int; } return; } my $results = timethese(1000000, { While => \&while_loop, ForEach => \&for_loop, }, 'none'); cmpthese( $results ); __END__ $ perl test.pl s/iter While ForEach While 2.32 -- -14% ForEach 1.98 17% --
One minor note here to point out, notice that the array @numbers will be destroyed due to shift. If you do not need to reuse the array then that could be a possible way of moving forward.
Hope this helps, BR.
In reply to Re: declare my variable in loop
by thanos1983
in thread declare my variable in loop
by gauss76
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |