To learn about Perl and OOP, I would like to create an object that gives access to an array.
During construction of the object, the array should be empty.
The accessor method should either return the array or if you pass an array to the method, the objects array contents should be changed.
Then I would like to implement a method that appends a variable to the array.
With a regular variable-attribute this would be:
Code:
package Example;
use strict;
use warnings;
sub new {
my ($class) = @_;
my $self = {
_someattribute => undef
}
sub someattribute {
my ($self, $someattribute ) = @_;
$self->{_someattribute} = $someattribute if defined($someattribute);
return $self->{_someattribute};
}
return(1);
Then I could access that variable like this:
Code:
#!/usr/bin/perl
use strict;
use warnings;
use Example;
my $example = new Example();
$example->someattribute('Test');
print $example->someattribute;
Can someone help me how this would look like for array-attributes?
/edit:
I found a solution that seems to work:
Code:
sub someattribute {
my ( $self, @someattribute ) = @_;
if (@_) { @{ $self->{someattribute} } = @_ }
return @{ $self->{someattribute} };
}