内容检查部分而非全部 class 属性
Content checking some, not all, class attributes
我有一个 class 有属性。我想检查是否定义了一些但不是全部。所以:
class A {
has $.a is rw;
has $.b is rw;
has $.c is rw;
has $.d is rw;
method delete { ... }
}
my A $x .= new(:a<hi>, :d<good>);
## later
$x.b = 'there';
## code in which $x.c may or may not be defined.
## now I want to check if the attributes a, b, and c are defined, without
## needing to know about d
my Bool $taint = False;
for <a b c> {
$taint &&= $x.$_.defined
}
这会导致错误,因为类型 A 的对象没有 'CALL-ME' 类型字符串的方法。
是否有一种内省方法可以为我提供 class 的属性值?
$x.^attributes
给出了它们的名称和类型,但没有给出它们的值。
我认为一定有一些方法,因为 dd
或 .perl
提供属性值 - 我认为。
是的,它被称为get_value
。它需要传递给它的属性的对象。例如:
class A {
has $.a = 42;
has $.b = 666;
}
my $a = A.new;
for $a.^attributes -> $attr {
say "$attr.name(): $attr.get_value($a)"
}
# $!a: 42
# $!b: 666
我有一个 class 有属性。我想检查是否定义了一些但不是全部。所以:
class A {
has $.a is rw;
has $.b is rw;
has $.c is rw;
has $.d is rw;
method delete { ... }
}
my A $x .= new(:a<hi>, :d<good>);
## later
$x.b = 'there';
## code in which $x.c may or may not be defined.
## now I want to check if the attributes a, b, and c are defined, without
## needing to know about d
my Bool $taint = False;
for <a b c> {
$taint &&= $x.$_.defined
}
这会导致错误,因为类型 A 的对象没有 'CALL-ME' 类型字符串的方法。
是否有一种内省方法可以为我提供 class 的属性值?
$x.^attributes
给出了它们的名称和类型,但没有给出它们的值。
我认为一定有一些方法,因为 dd
或 .perl
提供属性值 - 我认为。
是的,它被称为get_value
。它需要传递给它的属性的对象。例如:
class A {
has $.a = 42;
has $.b = 666;
}
my $a = A.new;
for $a.^attributes -> $attr {
say "$attr.name(): $attr.get_value($a)"
}
# $!a: 42
# $!b: 666