Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if a variable in Raku is set

Tags:

raku

I intentionally avoid the term defined because a variable may very well have a defined value but the .defined method will return false (Failures, for instance).

Is there any way to determine whether a variable has had a value set to it?

my $foo;
say $foo; # (Any), its type object, no value assigned
my Str $bar;
say $bar; # (Str), its type object, no value assigned
my $abc = Str;
say $abc; # (Str), the type object we assigned to $abc

How can we disinguish $bar (no value set, typed as Str) from $abc (value set to Str)?

Given that $bar.WHICH == $abc.WHICH, but $bar.VAR.WHICH !== $abc.VAR.WHICH, and methods like .defined will return false for each, is there any quick and easy way to determine that there is a set value?

I supposed it could be checked against the default value, but then there'd be no way to distinguish between the value being by virtue of unset, versus by being set in code.

like image 929
user0721090601 Avatar asked May 19 '20 06:05

user0721090601


1 Answers

You might try to assign a default value to a variable, instead of keeping it undefined:

 my Str $bar is default("");

$bar will be Str only if it's assigned that value type; if its value is deleted via assigning Nil it will default again to the empty string. As a matter of fact, the default for a variable is its type object, so:

my Str $foo;
my $bar = Str;
say $foo eqv $bar

will, in fact, return True.

like image 162
jjmerelo Avatar answered Sep 30 '22 23:09

jjmerelo