Hi Molks!

I'm just starting to get to grips with the OO features of Perl and i found this basic example on the forums Re: Algorithm::Treap and i've been playing around with it, which has resulted in a few questions

First of all, is there a preferred style for "new" constructors? Specifically one which will be taking hash value/key pairs as attributes?

Secondly, is there a way to tell how many objects have been created/exist in a particular class?

And lastly, what is the best way to access individual object attributes? Always through a method or can you access them directly?

Here's the basic code i was messing around with. As Always, any help and comments greatly appreciated!

#! /gte/bin/perl -w use strict; use warnings; my $obj=Numbers->new('num1'=>7, 'num2'=>2); print "The object attribute num1 is ",$obj->dump('num1'),"\n"; print "The object attribute num2 is ",$obj->dump('num2'),"\n"; $obj->add_nums(); print "The add result is ",$obj->dump('result'),"\n"; $obj->subtract_nums(); print "The subtract result is ",$obj->dump('result'),"\n"; package Numbers; # This is the class sub new { my $class=shift; my %params=@_; my $self={}; $self->{$_}=$params{$_} foreach keys(%params); bless($self, $class); return $self; } sub add_nums { my $self=shift; $self->{result}=$self->{num1}+$self->{num2}; return $self->{result}; } sub subtract_nums { my $self=shift; $self->{result}=$self->{num1}-$self->{num2}; return $self->{result}; } sub change_nums { my $self=shift; my %params=@_; $self->{$_}=$params{$_} foreach keys(%params); return $self; } sub dump { my $self=shift; my $val=shift; return $self->{$val}; } 1; __END__

In reply to OO best practice basic questions by Amblikai

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.