Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked

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:


... 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

Replies are listed 'Best First'.
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?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1067822]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (8)
As of 2017-04-25 09:31 GMT
Find Nodes?
    Voting Booth?
    I'm a fool:

    Results (449 votes). Check out past polls.