package Exp;
use 5.006;
use strict;
use warnings;
use Carp;
sub new{
my $class = shift;
my $validated = _validate( $_[0] );
return bless {
validated => $validated,
stored => [],
},$class;
}
sub _validate{
croak "No arg!" unless $_[0];
return $_[0];
}
sub store {
my $self = shift;
my $it = _validate( $_[0] );
push @{ $self->{ stored } }, new( $it ); # <---here NOT OK
}
1;
####
# croaks without arguments
perl -I . -MData::Dump -MExp -e " $exp=Exp->new(); dd $exp "
No arg! at -e line 1.
# OK with args
perl -I . -MData::Dump -MExp -e " $exp=Exp->new(2); dd $exp "
bless({ stored => [], validated => 2 }, "Exp")
####
perl -I . -MData::Dump -MExp -e " $exp=Exp->new(2); $exp->store(3) "
No arg! at -e line 1.
####
package ExpOk;
use 5.006;
use strict;
use warnings;
use Carp;
sub new{
my $class = shift;
my $validated = _validate( $_[0] );
return bless {
validated => $validated,
stored => [],
},$class;
}
sub _validate{
croak "No arg!" unless $_[0];
return $_[0];
}
sub store {
my $self = shift;
my $it = _validate( $_[0] );
push @{ $self->{ stored } }, bless{ validated => $it },__PACKAGE__; # <---here OK
}
1;
####
perl -I . -MData::Dump -MExpOk -e " $exp=ExpOk->new(2); $exp->store(3); dd $exp "
bless({ stored => [bless({ validated => 3 }, "ExpOk")], validated => 2 }, "ExpOk")