简体   繁体   中英

Perl array attribute inside an object

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);

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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM