given a rainy weekend I played a bit with a module of mines. All went well till night but then some tests failed in a weird way. I was, inside the main module restantiate some object via new() using parameters stores inside a container of the father object and I had all check done to validate arguments passed to new failed for childrens..
the situation is similar to the following Exp.pm
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;
If I use the module in the plain way all is well:
# 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")
But if now I call the store methods, it fails:
perl -I . -MData::Dump -MExp -e " $exp=Exp->new(2); $exp->store(3) " No arg! at -e line 1.
By other hands i found the following workaround using bless{ validated => $it },__PACKAGE__ instead of the new call: see the ExpOk.pm module:
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;
it works as (I) expected:
perl -I . -MData::Dump -MExpOk -e " $exp=ExpOk->new(2); $exp->store(3) +; dd $exp " bless({ stored => [bless({ validated => 3 }, "ExpOk")], validated => 2 + }, "ExpOk")
What happens with the first version of the module? Is my workaround a viable solution? Note that my intention is not to store children objects inside the father: in my project i store a configuration for various jobs to be executed and foreach one i instantiate a new object and i run it
thanks
L*
In reply to calling new inside the same module? by Discipulus
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |