There are conventional ways to handle the problem of attaching data to a Perl object (a blessed reference to something). If you have a reference to an array, then an "instance variable" is merely one member of the array. If you have a reference to a hash, then you can make named instance variables using the hash's key/value pairs.
By the use of use fields, you get a pseudo-hash -- that is, an array with named slots.
So for a short answer, here are some constructors that show the conventional addition of "instance variables" (I am deliberately not minimizing the code to avoid confusion):
package HashRefAsObject; sub new1 { # using a hash ref as an object my $class = shift; my $self = { }; # hash ref bless( $self, $class ); $self->{varA} = 123; # set "instvar" $self->{varB} = 456; # another return $self; } package ArrayRefAsObject; sub new2 { # using an array ref as an object my $class = shift; my $self = []; # array ref bless( $self, $class ); $self->[0] = 123; # set "instvar" $self->[1] = 456; # another return $self; } package Foo; # Using pseudo-hashes # from fields manpage: use fields qw(foo bar _Foo_private); sub new { my Foo $self = shift; unless (ref $self) { $self = fields::new($self); $self->{_Foo_private} = "this is Foo's secret"; } $self->{foo} = 10; $self->{bar} = 20; return $self; }
In reply to Re: Howto use hash instance vars?
by bikeNomad
in thread Howto use hash instance vars?
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |