in reply to Re: Scope of package variables
in thread Scope of package variables
tobyink clarified the difference between lexical variables and package variables, which I think I now understand. In the code below, I added a second print statement in MainFunction{}.
print("DumpValue: sv_a ... $ScopeTest::sv_a\n");Now, if the variable $sv_a is declared as my $sv_a = ..., then the message "Use of uninitialized value $ScopeTest::sv_a ..." is displayed and the program fails. But, if the variable $sv_a is declared as our $sv_a = ..., then the program runs just fine without any errors.
The final working code with $sv_a declared as a package variable is now:
#!/usr/local/bin/perl use 5.010; use strict; use warnings; package ScopeTest; our $sv_a = "scalar variable A"; sub dump_sv { print("DumpValue: sv_a ... $sv_a\n"); } sub new { my $obj_hv = {}; bless($obj_hv, $_[0]); } package main; MainFunction: { my $t_obj = ScopeTest->new(); $t_obj->dump_sv(); print("DumpValue: sv_a ... $ScopeTest::sv_a\n"); }
|
|---|