Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Content checking some, not all, class attributes

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.

like image 750
Richard Hainsworth Avatar asked Dec 29 '19 13:12

Richard Hainsworth


1 Answers

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
like image 167
Elizabeth Mattijsen Avatar answered Sep 23 '22 23:09

Elizabeth Mattijsen