getting hash reference from a package

B

Bill M

What is the correct syntax for accessing a hash reference from a package?

For example:

Package MyPackage;

my $foo = {
animals => ["cat", "dog", "fish"],
people => ["fred", wilma" ]
};

1;

and then (this is what I THINK should work) ...

use MyPackage;

foreach my $animal (@{$MyPackage::$foo->{animals}}) {
print $animal;
}


Thanks!!!
 
B

Bill M

Bill M wrote, On 3/13/2012 11:28 AM:
What is the correct syntax for accessing a hash reference from a package?

For example:

Package MyPackage;

my $foo = {
animals => ["cat", "dog", "fish"],
people => ["fred", wilma" ]
};

1;

and then (this is what I THINK should work) ...

use MyPackage;

foreach my $animal (@{$MyPackage::$foo->{animals}}) {
print $animal;
}


Thanks!!!

Sorry, I meant this:

use MyPackage;

foreach my $animal (@{$MyPackage::foo->{animals}}) {
print $animal;
}
 
T

Tim McDaniel

Bill M wrote, On 3/13/2012 11:28 AM:
What is the correct syntax for accessing a hash reference from a package?

For example:

package MyPackage;
my $foo = {
animals => ["cat", "dog", "fish"],
people => ["fred", "wilma" ]
};

1;

I added the missing double-quote before wilma and lowercased
"package".

"1;" usually comes at the end of a module file. So I assume that
that's in its own file, named MyPackage.pm.
use MyPackage;
Yeah, that requires a separate source file named MyPackage.pm or such.
foreach my $animal (@{$MyPackage::foo->{animals}}) {
print $animal;
}

Realize that "my" is lexical only.

(1) "my" does not create a package variable. There is no
$MyPackage::foo variable in MyPackage. When you refer to it in the
other file, it creates on that spot a variable set to undef.

(2) It's lexical only, so it exists only inside the file's scope.
It's not visible outside, so trying to refer to just "$foo" would get
you an error "Global symbol "$foo" requires explicit package name".

So replace "my" by "our" in MyPackage and it all works as you expect.
 
B

Bill M

Tim McDaniel wrote, On 3/13/2012 12:56 PM:
Bill M wrote, On 3/13/2012 11:28 AM:
What is the correct syntax for accessing a hash reference from a package?

For example:

package MyPackage;
my $foo = {
animals => ["cat", "dog", "fish"],
people => ["fred", "wilma" ]
};

1;

I added the missing double-quote before wilma and lowercased
"package".

"1;" usually comes at the end of a module file. So I assume that
that's in its own file, named MyPackage.pm.
use MyPackage;
Yeah, that requires a separate source file named MyPackage.pm or such.
foreach my $animal (@{$MyPackage::foo->{animals}}) {
print $animal;
}

Realize that "my" is lexical only.

(1) "my" does not create a package variable. There is no
$MyPackage::foo variable in MyPackage. When you refer to it in the
other file, it creates on that spot a variable set to undef.

(2) It's lexical only, so it exists only inside the file's scope.
It's not visible outside, so trying to refer to just "$foo" would get
you an error "Global symbol "$foo" requires explicit package name".

So replace "my" by "our" in MyPackage and it all works as you expect.
Thanks, just figured it out then saw your answer as I was about to reply
to myself.
 
M

Martijn Lievaart

Question: Is it proper to access a package variable directly? Would it
not be better to provide a method to retrieve the reference?

Even better, provide a getter and a setter (or combine them).

Something like:

my $global_debug_flag;

sub debugging {
$global_debug_flag = $_[0] if defined $_[0];
return $global_debug_flag;
}

M4
 
T

Tim McDaniel

Even better, provide a getter and a setter (or combine them).

That's certainly the fashion in object-oriented code. I may be
showing my ignorance, but I'm afraid I don't see the benefit in doing
that for a single uncomplicated global variable. An object with
complicated semantics, or semantics that must be constrained and
checked for validity, of course -- that's one of the points of
object-oriented code, and it's a very useful technique. But a simple
count, say, or a string that's unrelated to anything else? Why not
require getters and setters for that are visible for more than 50
lines, say, or for all variables?
 
R

Rainer Weikusat

Jack wrote:
: Question: Is it proper to access a package variable directly? Would it
: not be better to provide a method to retrieve the reference?

As a rule of thumb, pass parameters to subs and methods rather than
communicating through global variables. A singleton is a global variable
dressed in fancy clothes, so avoid those too.

A singleton is the Java programmer's workaround for the fact that
Java requires everything to be an instance of some class, that is,
a general blueprint for construction objects of certain kinds, but
that many real-world problems are easier dealt with by systems
constructed of stateful modules ('subsystems') providing some kind of
identifiable, useful functionality for solving a part of the original
problem (that's similar to complex real machines which are also
composed of cooperating 'sub-machines' dealing with 'subtasks' of the
problem supposed to be solved).

Apart from that, an object instance is a set of variables shared by
some set of cooperating subroutines and this is nothing but 'a global
variable dressed in fancy clothes'. Some people are convinced that
complex objects whose state changes over time are Evil[tm] and should
be avoided. Except when the result can be eaten, I presume ...
 
R

Rainer Weikusat

Ben Morrow said:
Quoth Jack said:
Question: Is it proper to access a package variable directly? Would it
not be better to provide a method to retrieve the reference?

If the value is truly global then there's very little point wrapping the
variable in a sub. A sub like

sub my_global { \$Foo }

or even

sub set_my_global { $Foo = $_[0] }

isn't hiding anything:

There might actually be an advantage in doing so: It helps with
debugging if all accesses to some object also go through a certain
piece of code, because this provides a location where debugging
statements or debugger breakpoints can be added.
 
R

Rainer Weikusat

[...]

Question: Is it proper to access a package variable directly? Would it
not be better to provide a method to retrieve the reference?

What do you mean by 'proper'? Eg, the typical example for something
where anything but enabling direct access to 'a package variable'
makes little sense would be some kind of 'debugging level' variable
which can be used to control the amount of diagnostics a program will
print: That's typically modified in one or two location (the code
which deal with command-line arguments and something like a signal
handler which can be used to change the value for a running program)
and read-only referenced from everywhere else in the code. This really
depends on the purpose of the variable.
 
R

Rainer Weikusat

Ben Morrow said:
Quoth Rainer Weikusat said:
Ben Morrow said:
Quoth Jack <[email protected]>:

Question: Is it proper to access a package variable directly? Would it
not be better to provide a method to retrieve the reference?

If the value is truly global then there's very little point wrapping the
variable in a sub. A sub like

sub my_global { \$Foo }

or even

sub set_my_global { $Foo = $_[0] }

isn't hiding anything:

There might actually be an advantage in doing so: It helps with
debugging if all accesses to some object also go through a certain
piece of code, because this provides a location where debugging
statements or debugger breakpoints can be added.

perldebug:
| w expr Add a global watch-expression. Whenever a watched global
| changes the debugger will stop and display the old and new
| values.

This is notoriously unreliable for 'non-managed code' (not applicable
to perl) and only the lesser half of the possible advantage. Also, I
wrote 'their might' for a reason: This depends on what debugging tools
can be used in a given situation and what their capabilities are.
 
R

Rainer Weikusat

Rainer Weikusat wrote
: A singleton is the Java programmer's workaround for the fact that
: Java requires everything to be an instance of some class, that is,
: a general blueprint for construction objects of certain kinds, but
: that many real-world problems are easier dealt with by systems
: constructed of stateful modules ('subsystems') providing some kind of
: identifiable, useful functionality for solving a part of the original
: problem (that's similar to complex real machines which are also
: composed of cooperating 'sub-machines' dealing with 'subtasks' of the
: problem supposed to be solved). [...]

The singleton pattern[1] isn't specific to Java even though denizens
of that language do tend to fetishize it. Java doesn't require
everything to be an instance of a class, the counterexample aside
from basic types being static methods. Even so, say we have the
module-qua-class

public class MyModule {
static int calls_ = 0;

public static void SayHi() {
++calls_;
System.out.println("Hello!");
}

public static void SayBye() {
++calls_;
System.out.println("Good-bye!");
}

public static int Calls() {
return calls_;
}
}

MyModule fits your description above, but it is not a singleton.
The name of the pattern derives from the constraint that a system
may have at most a single instance of such a class. You might claim
that a bag of static methods meets the definition in its vacuous
sense, but such usage robs the term of its meaning.

Since there's no class instance in the example above, it obviously
doesn't make sense to call it 'a singleton'. OTOH, both serve the
same purpose: Express the concept of 'a subsystem', that is, some set
of state variables shared by some set of 'public' interface routines
intended to solve a subproblem of the problem the program containing
this code is supposed to solve, in Java. For the purpose of this
discussion, ie, the 'global variable dressed in fancy clothes' issue,
both have the same properties and there's actually nothing wrong with
that: A subsystem is isomorph to a single instance of some class
(that's exploited by the so-called 'singleton pattern') and this
implies that any single object is nothing but 'a fancily dressed
global variable'.
Rather than imposing the single-instance constraint, creating a
singleton as a shortcut to bypass threading the instance through
the call graph is a frustratingly common practice.

Hmm ... what is this supposed to mean?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top