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