A nifty little trick I like to use is to pull @_ directly into the "new" object. This works nicely when @_ contains a hashref.

Example:

#!/usr/bin/perl use warnings; use strict; my $object = MyObject->new( name => 'MyNewObject', debug => 1 ); print "MyObject Name: $object->{name}\n"; print "Debug setting: $object->{debug}\n"; package MyObject; sub new { print "method 'new' called with parameters: ", join ("\n", @_ ), "\n +"; my $class = shift my $self = {@_}; $self -> {state} = "newly created"; bless $self, $class; return $self; }
Doing it this way allows you to assign attributes (variables) to the new object when it is created/instantiated.

Another cool feature of perl objects is that you don't need to explicitly define "getters" and "setters", since all they really do is get or set an attribute value. You can accomplish the same thing by getting or setting the attribute value directly (like you would with any other hashref)

$object->{attribute} = 'value'; #setter print "$object->{attribute}\n"; #getter

In reply to Re: Object Oriented Perl - very basic guide by bcarroll
in thread Object Oriented Perl - very basic guide by Preceptor

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.