Home > Raku > Symbolism


On IRC deoac wished to know how to print the name of a variable. This question is ambiguous. To get the name of the container is easy.

my $foo;
say $foo.VAR.name;
# OUTPUT: $foo

If binding or constants involved, things get odd or fail.

my $bar := $foo;
constant $never-changes = 'war';
# OUTPUT: $foo
          No such method 'name' for invocant of type 'Str'.  Did you mean any of
          these: 'Date', 'Num', 'are', 'none', 'note', 'take'?

The second meaning of “variable” might be “symbol” for deoac’s use case. Getting hold of a symbol name requires early compile time measures.

use experimental :macros;
macro symbol-name($symbol) {
    quasi { $symbol.Str }

say symbol-name($foo);
say symbol-name($bar);
say symbol-name($never-changes);
# OUTPUT: ($foo)

The value of $symbol is an AST object and stringifies (in this case) to a list of Str. I didn’t dig deeper, because with RakuAST things will change.

However, this once again shows that we might do better by explaining what my actually does instead of assuming that one can guess what we mean when using the term “variable”.

Categories: Raku
  1. No comments yet.
  1. August 15, 2022 at 13:35

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: