Perl: Why is it slower to declare (my) variables inside a loop?

后端 未结 5 1376
余生分开走
余生分开走 2021-01-12 20:58

What\'s the difference, from the interpreter\'s POV, between the following the following programs:

#!/usr/bin/perl -w

use strict;

for (1..10000000) {
    m         


        
5条回答
  •  时光取名叫无心
    2021-01-12 21:34

    1. Declaring my outside the loop causes the declaration to occur once. During the declaration, the perl reserves memory for that variable.

    2. Declaring my inside the loop causes the declaration to occur at each interval of the loop.

    my is Perl's answer to declaring a variable locally - local was used for something else and does not means the same thing as what it would mean in C. When you declare the variable inside the loop, it is declared in local scope to the loop block, where the block starts/ends at each interval. Not only is the variable declared, but it may also be cleaned up (dereferenced and/or set to undef) at the end of the block (though this changes from Perl versions).

    Variables declared outside the loop block are considered "global" (not literally, but in the sense of the loop block). These variables reuse their memory locations, rather than having to search for new addresses.

提交回复
热议问题