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");
}
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.