Declaring variables inside or outside loops in Perl, best practice

I have worked on some Perl data mining libraries. Libraries are full of nested loops for collecting and processing information. I work with strict mode, and I always declare my variables from myoutside the first loop. For example:

# Pretty useless code for clarity purposes:

my $flag = 1;
my ($v1, $v2);

while ($flag) {
  for $v1 (1 .. 1000) {

    # Lots and lots of code...

    $v2 = $v1 * 2;
  }
}

For what I read here , in terms of efficiency, it is better to declare them outside the loop, however, maintenance of my code is becoming more and more as the declaration of some variables ends quite far from where they are actually used.

Something like this would be easier to accomplish:

my $flag = 1;

while ($flag) {
  for my $v1 (1 .. 1000) {

    # Lots and lots of code...

    my $v2 = $v1 * 2;
  }
}

Perl, ++. - , , Perl, .

Perl- ?

+4
4

, .

, for.

(, $flag), .

, , , , , .

, , , ; , .

+14

. . . , , .

, , , , . , .

, , , push @array, $elem, . , , . , , .

+4

, , . , , .

0

The specific example you specified (declaration of a loop variable) probably does not have a performance penalty. As the link you quoted says that the reason for the difference in performance comes down to whether the variable is initialized inside the loop. In the case of a for loop, it will be initialized anyway.

I almost always declare variables in the innermost region possible. This reduces the likelihood of errors. I would only change this if performance became a problem in a particular loop.

0
source

Source: https://habr.com/ru/post/1523632/


All Articles