1

Tried to write a perl module with OOP, but it can add an object to an array, when I use Dump method, it will output wrong data like this. Where is my error ?

Thanks

bless( {
                 '_name' => 'CUSIP',
                 '_validation_array' => [],
                 '_seq' => '1'
               }, 'Field' );

source code:

 package Field;

    sub new {
    my $class = shift;
    my $self = {
        _name => shift,
        _seq => shift,
        _validation_array => [ @_ ],
    };

    bless($self, $class);
    return $self;
};

sub pushValidation(){
    my $validation = shift;   
    push(@{$self->{_validation_array}}, $validation);     
};

sub dump(){
    foreach my $validation (@{$self->{_validation_array} })   {
        #print Dumper($validation);#will work, 
        print $validation->{name}; #error, Use of uninitialized value
    }
}        
    1;

This is the way I call this method :

my $validationObj = new Validation($validation->{name}, $validation->{seq});
$field->pushValidation($validationObj);
0

1 Answer 1

6

I see several problems here, but the most serious one is here:

sub pushValidation() {
    my $validation = shift;   
    push(@{$self->{_validation_array}}, $validation);     
};

This function is expecting a $self argument, but isn't shifting it from the arguments. You need to add use strict; at the top of your Perl file. If it had been enabled, the issue would have been immediately obvious:

Global symbol "$self" requires explicit package name at <filename> line <line>.

Same thing goes for the dump() function. (By the way, dump is a bad method name, as there is an (obscure) Perl builtin function with the same name. But that's not a huge issue.)

Sign up to request clarification or add additional context in comments.

4 Comments

correct, I put the 'use strict', I see this error. how to fix it ?
You need to shift out $self as the first argument to the function - e.g, add my $self = shift; before the $validation argument. Alternatively, unpack both at one: my ($self, $validation) = @_;.
I made this change, inside the dump, use print $validation->{name}; still get error, "Use of uninitialized value in print"
As I believe someone else pointed out in a comment, some of your attribute references have leading underscores (e.g, $self->{_name}) and some don't ($self->{name}). Either one will work, but you need to be consistent.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.