在Perl Moo对象中自动将空字符串转换为undef

时间:2016-09-15 15:40:34

标签: perl attributes moo

对于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.

请帮助了解错误的原因。

1 个答案:

答案 0 :(得分:2)

为什么不对coerce属性in 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上方(上面链接)。