动态数组作为类成员

时间:2013-05-08 15:12:42

标签: arrays perl class

有以下课程:

package MyClass;

use strict;
use warnings;

sub new
{
    my $class = shift();
    my $self = {
        _class_array => []
};

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

如何设置/获取此数组的值?

我尝试了以下代码:

sub AddDataType
{
    my $self = shift();
    my $new_element = shift();
    my @array = $self->{_class_array};

    print("Number of elements ".($self->{_class_array})."\n");
    push(@array, $new_element);
    $self->{_class_array} = @array;

    print("Element added. Number of elements ".($self->{_class_array})."\n");
}

输出如下:

  

元素数量ARRAY(0x21bb4c)

     

添加了元素。类型数量2

     

元素数量2

     

添加了元素。类型数量2

     

元素数量2

     

添加了元素。类型数量2

问题是:

  1. 这是什么意思:Number of elements ARRAY(0x21bb4c)
  2. 为什么数组长度始终保持2

3 个答案:

答案 0 :(得分:3)

您正在使用arrayref作为数组。试试:

sub AddDataType {
    my ( $self, $new_element ) = @_;

    print "Number of elements " . scalar @{ $self->{_class_array} } . "\n"; 
    push @{ $self->{_class_array} }, $new_element;
    print "Element added. Number of elements " . scalar @{ $self->{_class_array} } . "\n";

    return;
}

答案 1 :(得分:2)

正如其他人所说,你的数组类元素是一个数组引用。你的方法应该是这样的

sub AddDataType {
    my ($self, $new_element) = @_;
    my $array = $self->{_class_array};
    print "Number of elements " . scalar @$array . "\n";
    push @$array, $new_element;
    print "Element added. Number of elements " . scalar @$array . "\n";
}

答案 2 :(得分:1)

你已经得到了很好的答案。我只想提一下Moose traits能真正使这种属性变得简单/有趣。

BEGIN {
    package MyClass;
    use Moose;
    has "data" =>
        traits  => ["Array"],
        is      => "ro",
        isa     => "ArrayRef[Str]",
        default => sub { [] },
        handles => {
            AddDataType => "push",
            DataCount   => "count",
            NoData      => "is_empty",
            AllData     => "elements",
        };
}

my $thingy = MyClass->new();
print "DOES HAS DATAS? ", $thingy->NoData ? "NOE" : "YES", $/;
$thingy->AddDataType("OHAI");
print "CAN HAS DATA? ", $thingy->NoData ? "NOE" : "YES", $/;
$thingy->AddDataType(qw/ ANUDDER CUPLA HERE / );
print "I HAZ DATAS: ", $thingy->DataCount, $/;
print "HERE DEY IS: ", join(", ", $thingy->AllData), $/;

__DATA__
DOES HAS DATAS? NOE
CAN HAS DATA? YES
I HAZ DATAS: 4
HERE DEY IS: OHAI, ANUDDER, CUPLA, HERE