Hi All,

This is a fascinating answer I got back from Chat GPT:

-T


raku: I am going to be pushing (with push) various variables
unto an array: strings, integers, classes, etc..   Is there
a way to ask a cell in the array what type of data is in them?

Yes. In Raku, every object knows its type.

The most direct way is to use the .WHAT method:

my @a;
@a.push("hello");
@a.push(42);
@a.push(3.14);

class Person { }
@a.push(Person.new);

for @a -> $item {
    say $item.WHAT;
}

Output:

(Str)
(Int)
(Rat)
(Person)

If you want just the type name without the surrounding parentheses:

say $item.^name;

Output:

Str
Int
Rat
Person

Testing for a specific type

Usually, instead of asking what the type is, you ask whether it is a given type using ~~ (smartmatch):

given $item {
    when Str { say "It's a string" }
    when Int { say "It's an integer" }
    when Person { say "It's a Person" }
    default { say "Something else: {$item.^name}" }
}

or

if $item ~~ Int {
    say "Integer";
}
elsif $item ~~ Str {
    say "String";
}
Checking the exact type

If you need to know the exact type (not a subclass), you can compare .WHAT:

if $item.WHAT === Int {
    say "Exactly an Int";
}
Example with a mixed array
class Dog { }

my @things = (
    "abc",
    123,
    4.56,
    Dog.new
);

for @things -> $x {
    say "{$x.perl} is a {$x.^name}";
}

Output:

"abc" is a Str
123 is a Int
4.56 is a Rat
Dog.new is a Dog

In idiomatic Raku, ~~ is generally preferred when you're
making decisions based on type, while .^name or .WHAT are
more useful for introspection or debugging.


Reply via email to