I have two classes say A and B, i need to set a static variable in Class A (like static variables in Java ), and access the variable from class B (using ClassName.variable name in Java ). Can i do something like this in Perl .
Thanks in advance
I have two classes say A and B, i need to set a static variable in Class A (like static variables in Java ), and access the variable from class B (using ClassName.variable name in Java ). Can i do something like this in Perl .
Thanks in advance
tree .
├── foo.pl
└── lib
├── A.pm
└── B.pm
cat lib/A.pm
package A;
use strict;
use warnings;
our $foo = 7;
1;
cat lib/B.pm
package B;
use strict;
use warnings;
use feature qw/ say /;
use A;
say $A::foo;
1;
cat foo.pl
#!/usr/bin/env perl
use strict;
use warnings;
use B;
perl -Ilib foo.pl
7
I don't know Java really so I'm guessing that what you mean by "static variable" is something to do with scoping? In perl 'my' and 'our' are the ways you can control scope, but I believe I am correct in saying hat packages/modules make variable's scope "private" to the .pm
file they are declared in (correct this and/or elaborate further fellow perlistas!).
As for how to "access" them hmm my copy of Programming Perl (2nd Edition) covers this in chapter 2 in the section on Scoped Declarations. But here's a pithy (slightly edited) part of the first footnote from page 107:
Packages are used by libraries, modules, and classes to store their own private data so it doesn't conflict with data in your main program. If you see someone write
$Some::stuff
they're using the $stuff scalar variable from the packageSome
.
The Exporter documentation and this perlmonks node about global variables might help you get clearer in your thinking about variables and scope in perl. The classic perlmonks node - Variable Scoping in Perl: the basics - is a frequently consulted reference :-)
If you already know how to program (i.e. in Java) sometimes another good reference (only slightly dated) for "how to" do things in Perl is The Perl Cookbook - excerpts of which you can find online.
Cheers,