你如何让MotherDogRobot使用地图和散列哈希来生成一系列小狗对象?

时间:2011-10-11 07:57:09

标签: perl oop object hash

使用(General :: Config)从配置文件中读取Puppy元数据并创建哈希哈希

$puppy_hashes = {
 puppy_blue => { name => 'charlie', age => 4 },
 puppy_red  => { name => 'sam', age => 9 },
 puppy_yellow  => { name => 'jerry', age => 2 },
 puppy_green  => { name => 'phil', age => 5 },
}

MotherDogRobot包消耗了小狗哈希出生的一系列小狗对象(笑)

package MotherDogRobot;  
use Moose;
use Puppy;
use Data::Dumper;
#moose includes warn and strict

sub init_puppy{
  my($self,%options) = @_;
  my $puppy = Puppy->new( %options );
  return ($puppy);
}

sub birth_puppies{
  my($self,$puppy_hashes) = @_;
  my @keys = keys %{$puppy_hashes};
  my @puppies = map { $self->init_puppy( $puppy_hashes->{$_} ) } @keys;
  return(@puppies);
}

sub show_me_new_puppies{
  my($self,$puppy_hashes) @_;
  print Dumper($self->birth_puppies($puppy_hashes));
}

错误奇数个参数

将%选项传递给Puppy-> new(%options)

没有幸运的分娩小狗 - 这意味着我不能把激光放在头上= /

更新

我认为问题在于我将Hash Ref传递给init_puppy()而不是数组或散列,所以当我尝试将%选项传递给新构造函数时,它没有得到正确的(key => value)对 - 因此奇数个参数错误。

但是从这个角度来看,我一直在研究这段代码,我无法弄清楚如何正确地解除这个问题。

顺便说一下,这是我使用Perl的第22天!

2 个答案:

答案 0 :(得分:3)

你正在使用空变量,好像它们不是空的,也就是说,你根本没有做任何事情

print "hi $_ " for my @foo;

这假设您展示的不完整代码段是您真正使用的

更新:同样在子init_puppy中,您永远不会初始化my($self,%options)= @_;

#!/usr/bin/perl --
use strict;
use warnings;
Main( @ARGV );
exit( 0 );
sub Main {
    my $puppy_hashes = {
        puppy_blue   => { name => 'charlie', age => 4 },
        puppy_red    => { name => 'sam',     age => 9 },
        puppy_yellow => { name => 'jerry',   age => 2 },
        puppy_green  => { name => 'phil',    age => 5 },
    };

    for my $puppy ( MotherDogRobot->birth_puppies($puppy_hashes) ) {
        print join ' ', $puppy, $puppy->name, $puppy->age, $puppy->dump, "\n";
    }
}

BEGIN {
    package Puppy;
    BEGIN { $INC{'Puppy.pm'} = __FILE__; }
    use Any::Moose;
    has 'name' => ( is => 'rw', isa => 'Str' );
    has 'age'  => ( is => 'rw', isa => 'Int' );

    package MotherDogRobot;
    BEGIN { $INC{'MotherDogRobot.pm'} = __FILE__; }
    use Moose;
    use Puppy;

    sub init_puppy {
        my ( $self, %options ) = @_;
        my $puppy = Puppy->new(%options);
        return ($puppy);
    }

    sub birth_puppies {
        my ( $self, $puppy_hashes ) = @_;
        my @puppies = map { $self->init_puppy( %{$_} ) } values %$puppy_hashes;
        return (@puppies);
    }
    no Moose;
}

答案 1 :(得分:1)

标准的Moose构造函数将同时接受

->new( %{ $puppy_hashes->{$_} } )

->new( $puppy_hashes->{$_} )

如果$puppy_hashes包含您所说的内容,则$_是现有密钥。

此外,当您不传递任何参数时,Moose不会给出错误Error odd number of argments。 (您没有为%config分配任何内容。)

我不知道你说的是哪一部分是错的,但你所说的并没有加起来。