Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re: Scope of package variables

by tobyink (Abbot)
on Dec 19, 2013 at 14:22 UTC ( #1067822=note: print w/ replies, xml ) Need Help??


in reply to Scope of package variables

It is in scope. It's just currently set to undef. You're executing this line:

$t_obj->dump_sv();

... before you execute this line:

my $sv_a = "scalar variable A";

So $sv_a has no value yet.

This, for example, works:

#!/usr/local/bin/perl use 5.010; use strict; use warnings; my $sv_a; MainFunction: { $sv_a = "scalar variable A"; my $t_obj = ScopeTest->new(); $t_obj->dump_sv(); } package ScopeTest; sub dump_sv { print("DumpValue: sv_a ... $sv_a\n"); } sub new { my $obj_hv = {}; bless($obj_hv, $_[0]); } 1;

Being pedantic, variables declared with my are not "package variables", but "lexical variables". Package variables are those declared with our (in fact, these are lexical aliases to package variables), or those that are not declared at all.

use Moops; class Cow :rw { has name => (default => 'Ermintrude') }; say Cow->new->name


Comment on Re: Scope of package variables
Select or Download Code
Re^2: Scope of package variables
by rongrw (Novice) on Dec 21, 2013 at 03:42 UTC
    Thank you Monks, for all your great suggestions to my recent question. The approach I took was to move the MainFunction block below the definition of the package ScopeTest. This solved the problem nicely. I've added the final code to the bottom of this post.

    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"); }

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1067822]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (9)
As of 2014-09-19 07:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (132 votes), past polls