迭代一个Class :: Struct对象数组

时间:2018-04-15 10:09:32

标签: perl

我正在使用Class::Struct模块 并且有两个结构,CatKittenCat是一只母猫,Cat的一个属性应该是Kitten个对象的数组。我很难做到这一点。

如果我将kittens数组保存为对象,我无法按预期迭代它;我只得到一个带有一个看似是数组的元素的数组。如果我将它保存为参考,我无法弄清楚如何正确地推理它。

#!/usr/bin/perl

use strict;
use warnings;

use Class::Struct;
use Data::Dumper;

struct Cat => [
    name    => '$',
    age     => '$',
    kittens => '$',
];

struct Kitten => [
    name => '$',
    age  => '$',
];

my $lil_kitten = Kitten->new( name => 'Lil Socks', age => 2 );
my $big_kitten = Kitten->new( name => 'Big Socks', age => 3 );
my $old_kitten = Kitten->new( name => 'Old Socks', age => 4 );

my @kitten_array = ( $lil_kitten, $big_kitten, $old_kitten );

my $kitten_count = scalar @kitten_array;
print "There were $kitten_count kittens\n";

foreach my $k ( @kitten_array ) {
    bless $k, 'Kitten';
    print "Kitten: ", $k->name, " is ", $k->age, " years old.\n";
    print Dumper($k), "\n";
}

my $cat = Cat->new( name => 'Socks' );
$cat->age(17);
#$cat->kittens(@kitten_array);
$cat->kittens(\@kitten_array);

my $ref_type = $cat->kittens;
print "Ref type: ", $ref_type, "\n\n\n\n";
#$kitten_count = scalar @$cat->kittens;
#print "There were $kitten_count kittens\n";

print "Once a cat called ", $cat->name, " who was ", $cat->age, "\n";
#foreach my $kat(@$cat->kittens) {
foreach my $kat($cat->kittens) {
    bless $kat, 'Kitten';
    print "Kitten: ", $kat->name, " is ", $kat->age, " years old.\n";
    print Dumper($kat), "\n";
}

1 个答案:

答案 0 :(得分:5)

你应该初始化小猫'成为一个数组(使用'@')并在取消引用中使用大括号作为优先级。我已使用评论# CHANGED标记了已更改的行。

#!/usr/bin/perl
use strict;
use warnings;
use Class::Struct;
use Data::Dumper;

struct Cat =>
[
    name     => '$',
    age     => '$',
    kittens  => '@',   # CHANGED
];

struct Kitten =>
[
  name     => '$',
  age     => '$',
];

my $lil_kitten = Kitten->new( name => 'Lil Socks', age=> 2);
my $big_kitten = Kitten->new( name => 'Big Socks', age=> 3);
my $old_kitten = Kitten->new( name => 'Old Socks', age=> 4);

my @kitten_array = ($lil_kitten, $big_kitten, $old_kitten);

my $kitten_count = scalar @kitten_array;
print "There were $kitten_count kittens\n";

foreach my $k(@kitten_array) {
  bless $k, 'Kitten';
  print "Kitten: ", $k->name, " is ", $k->age, " years old.\n";
  print Dumper($k), "\n";
}

my $cat = Cat->new( name => 'Socks');
$cat->age(17);
#$cat->kittens(@kitten_array);
$cat->kittens(\@kitten_array);

my $ref_type = $cat->kittens;
print "Ref type: ", $ref_type, "\n\n\n\n";
$kitten_count = scalar @{$cat->kittens};   # CHANGED
print "There were $kitten_count kittens\n";

print "Once a cat called ", $cat->name, " who was ", $cat->age, "\n";

#foreach my $kat(@$cat->kittens) {
foreach my $kat($cat->kittens) {
    bless $kat, 'Kitten';
    print "Kitten: ", $kat->name, " is ", $kat->age, " years old.\n";
    print Dumper($kat), "\n";
}

@$cat->kittens的问题在于它首先取消引用$cat成为数组,然后尝试在该数组上调用方法kittens()。这涉及Perl尝试通过将@$cat转换为字符串来解释scalar @$cat作为类名 - 即"3"->kittens(),这是数组的大小。你最终打电话给EmguCV