1

对于 Perl Moo 对象的某些字段,我想在将空字符串分配给带有undef.

那就是我想要的:$obj->x("")使该字段x未定义。

请帮助开发一个这样做的 Moo 扩展。


一种可能的方法:

sub make_field_undef {
  my ($class, $field_name) = @_;
  eval "package $class";
  around $field_name => sub {
    my $orig = shift;
    my $self = shift;
    my @args = @_;
    if(@args >= 1) {
      $args[0] = undef if defined $args[0] && $args[0] eq '';
    }
    $orig->($self, @args);
  };
}

但是有没有“更结构化”或“更具声明性”的方式来做到这一点?还有其他方法可以做到这一点吗?


下面是我实现它的完整示例。但是运行它会产生我不明白的错误:

package UndefOnEmpty;
use Moo;

sub auto_undef_fields { () }

sub make_fields_undef {
  my ($class) = @_;
  eval "package $class";
  around [$class->auto_undef_fields] => sub {
    my $orig = shift;
    my $self = shift;
    my @args = @_;
    if(@args >= 1) {
      $args[0] = undef if defined $args[0] && $args[0] eq '';
    }
    $orig->($self, @args);
  };
  around 'BUILD' => {
    my ($self, $args) = @_;
    foreach my $field_name ($class->auto_undef_fields) {
      $args->{$field_name} = undef if defined $args->{$field_name} && $args->{$field_name} eq "";
    }
  };
}

1;

使用示例:

#!/usr/bin/perl

package X;
use Moo;
use lib '.';
extends 'UndefOnEmpty';
use Types::Standard qw(Str Int Maybe);
use Data::Dumper;

has 'x' => (is=>'rw', isa=>Maybe[Str]);
has 'y' => (is=>'rw', isa=>Maybe[Str]);

sub auto_undef_fields { qw(x y) }
__PACKAGE__->make_fields_undef;

my $obj = X->new(x=>"");
$obj->y("");
print Dumper $obj->x, $obj->y;

以下是错误:

$ ./test.pl 
"my" variable $class masks earlier declaration in same scope at UndefOnEmpty.pm line 20.
"my" variable $args masks earlier declaration in same statement at UndefOnEmpty.pm line 21.
"my" variable $field_name masks earlier declaration in same statement at UndefOnEmpty.pm line 21.
"my" variable $args masks earlier declaration in same statement at UndefOnEmpty.pm line 21.
"my" variable $field_name masks earlier declaration in same statement at UndefOnEmpty.pm line 21.
syntax error at UndefOnEmpty.pm line 20, near "foreach "
Compilation failed in require at /usr/share/perl5/Module/Runtime.pm line 317.

请帮助了解错误的原因。

4

1 回答 1

2

为什么不使用带有incoerce属性的强制转换?这似乎是最简单直接的方法。has

package Foo;
use Moo;

has bar => (
    is     => 'rw',
    coerce => sub { $_[0] eq q{} ? undef : $_[0] },
);

这就是对象当时的样子。

package main;
use Data::Printer;
p my $foo1 = Foo->new( bar => q{} );
p my $foo2 = Foo->new( bar => 123 );
p my $foo3 = Foo->new;

__END__

Foo  {
    Parents       Moo::Object
    public methods (2) : bar, new
    private methods (0)
    internals: {
        bar   undef
    }
}
Foo  {
    Parents       Moo::Object
    public methods (2) : bar, new
    private methods (0)
    internals: {
        bar   123
    }
}
Foo  {
    Parents       Moo::Object
    public methods (2) : bar, new
    private methods (0)
    internals: {}
}

在 Moose 中,您还可以定义自己的类型,该类型派生自您的Str并具有内置强制。然后,您可以将所有属性设为该类型并打开强制。

为了让 Moo 表现得像这样,请查看文档has和属性isa,它就在上面coerce(上面链接)。

于 2016-09-16T07:01:42.953 回答