As others have pointed out, you're not returning a blessed object from your new method. The blessed object would usually be a hashref (doesn't have to be though, other references are fine), and it is quite common to use that hashref to store the internal data about the object.
Here's an example of a simple object representing a bag for keeping things in. The bag has a colour and some contents. There are methods for painting the bag a new colour, for adding an item to the contents, and for checking if it's empty.
use v5.12; use Data::Dumper (); { package Backpack; sub new { # the constructor my $class = shift; my %params = @_==1 ? %{$_[0]} : @_; my $self = bless {}, $class; $self->colour($params{'colour'} || 'black'); $self->contents($params{'contents'} || []); return $self; } sub colour { # a so-called "accessor" method my $self = shift; $self->{colour} = $_[0] if @_; return $self->{colour}; } sub contents { # another "accessor" method my $self = shift; $self->{contents} = $_[0] if @_; return $self->{contents}; } sub is_empty { my $self = shift; return (@{$self->contents} == 0); } sub add_item { my $self = shift; my ($item) = @_ or die "what item??\n"; push @{$self->contents}, $item; return $self; } sub paint { my $self = shift; my ($colour) = @_ or die "what colour??\n"; $self->colour($colour); return $self; } sub dump { my $self = shift; Data::Dumper::Dumper($self); } } my $x = Backpack->new(colour => "Red"); $x->add_item("keys"); $x->add_item("mobile phone"); $x->add_item("mobile phone charger"); my $y = Backpack->new(contents => ["pants"]); print $x->dump, $y->dump;
That should be enough to show you what's going on.
Writing OO in Perl tends to require a lot of "boilerplate" code - for example the constructor and the accessors. For this reason many people use class builder modules. The most popular one at the moment is Moose which also has a faster, lighter-weight companion Moo if your OO needs are simple. I recommend checking both of these out. Here's the Backpack example written using Moose:
use v5.12; { package Backpack; use Moose; has colour => ( accessor => 'colour', writer => 'paint', default => sub { 'black' }, ); has contents => ( traits => ['Array'], accessor => 'contents', default => sub { [] }, handles => { add_item => 'push', is_empty => 'is_empty', }, ); } my $x = Backpack->new(colour => "Red"); $x->add_item("keys"); $x->add_item("mobile phone"); $x->add_item("mobile phone charger"); my $y = Backpack->new(contents => ["pants"]); print $x->dump, $y->dump;
As you can see, it's halved the amount of code we've had to write.
In reply to Re: Module authoring and OO perl
by tobyink
in thread Module authoring and OO perl
by jellisii2
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |