I have a class with attributes. I want to check whether some but not all are defined. So:
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
}
This will cause errors because an object of type A doesn't have a method 'CALL-ME' for type string.
Is there an introspection method that gives me the values of attributes of a class?
$x.^attributes
gives me their names and types, but not their values.
I think there must be some way since dd
or .perl
provide attribute values - I think.
Yes, it is called get_value
. It needs the object of the attribute passed to it. For example:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With