First, understand that Perl's OO support does not actually include the concept of instance variable. Perl does not provide, for instance, for data inheritance (though you can do it yourself). What we have instead are blessed references to certain primitive things: arrays, hashes, scalars, subroutines.

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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.