Difference between BLOCK and Perl Coverage Function

Guys, I'm a little confused, I played with glasses in Perl when I came across this:

#! usr/bin/perl use warnings; use strict; sub nested { our $x = "nested!"; } print $x; # Error "Variable "$x" is not imported at nested line 10." print our $x; # Doesn't print "nested!" print our($x) # Doesn't print "nested!" 

But when I do this:

 { our $x = "nested"; } print our($x); # Prints "nested" print our $x; # Prints "nested" print $x; # Prints "nested" 

So guys, can you explain to me why they work, and not?

+6
source share
2 answers
  • To explain why the block example works the way it does, consider our explanation from the โ€œModern Perlโ€ book, chapter 5

    Our area

    Within this scope, declare an alias for the package variable with our built-in.
    A full name is available everywhere, but the lexical alias is displayed only within its capabilities.

    This explains why the first two fingerprints of your second example work (ours is re-declared in the print area), while the third is not (like our only $ x aliases for the package variable within the block area). Note that printing $main::x will work correctly - it is only an alias that is bound to a block, not the package variable itself.


  • Regarding the function:

    • print our $x; and print our($x) "do not work", namely, they correctly state that the value is not initialized - since you never called a function that would initialize this variable. Note the difference:

       c:\>perl -e "use strict; use warnings; sub x { our $x = 1;} print our $x" Use of uninitialized value $x in print at -e line 1. c:\>perl -e "use strict; use warnings; sub x { our $x = 1;} x(); print our $x" 1 
    • print $x; will not work for the same reason as with the block - our only the scope of applying the alias to the block (i.e. in this case is the body of the sub), so you MUST either rename it in the area of โ€‹โ€‹the main block (according to the example print our $x ), OR use the fully qualified global package outside the subdirectory, in which case it will behave as expected:

       c:\>perl -e "use strict; use warnings; sub x { our $x = 1;} print $main::x" Use of uninitialized value $x in print at -e line 1. c:\>perl -e "sub x { our $x = 1;} x(); print $main::x" 1 
+5
source

To echo DVK's answer, our is just a convenient anti-aliasing tool. Each variable used in these examples is actually called $main::x . Within any lexical domain, you can use our to alias this variable with an abbreviated name in the same domain; the variable is not reset or is deleted externally, but only an alias. This is not like the my keyword, which makes a new variable related to this lexical scope.

+6
source

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


All Articles