1

有以下类:

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
4

3 回答 3

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;
}
于 2013-05-08T15:17:30.190 回答
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";
}
于 2013-05-08T15:25:37.173 回答
1

你已经得到了很好的答案。我只想提一下Moose的特质真的可以让这种属性变得简单/有趣。

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
于 2013-05-08T17:24:08.383 回答