Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Colons in variables

Tags:

syntax

raku

Colons can be used as part of a variable name in Perl 6, together with angle brackets. These are apparently called extended identifiers, and are used to define things such as infix:<+>.

my $foo:bar = 3;
my $foo:bar<2> = 2;
my $foo:bar<baz> = 'quux';
say $foo:bar; # 3
say $foo:bar<2>; # 2 (and so on)

This creates identifiers with the same name in the current scope

say MY::.keys; 

Prints ($=pod $_ $/ $buz !UNIT_MARKER $=finish EXPORT $foo:bar<2> $foo:bar<baz> $! ::?PACKAGE GLOBALish $bur::quux $¢ $foo:bar $?PACKAGE

But here's the thing.

say $foo:bar.kv; # prints key-value pairs.

print (0 3). So these coloned variables are creating a key-value pair. However, the other two "keys" (2 and baz) are not included in that set of key-value pairs. And if we really try to do say $foo:bar{'0'} or say $foo:bar<0>; we will obtain different errors, so there does not seem to be an actual way of using that as a real key. So I guess there are at least a couple of questions here:

  1. Are these key-value pairs "real", or simply an unintended effect of something completely different?
  2. If it is, can you define other values? Why are not the other "keys" included in that set?
  3. Is there any user-facing way of getting all "angled" keys defined for a particular extended identifier? For instance, a way of obtaining all infix variables?
like image 656
jjmerelo Avatar asked Jun 15 '18 17:06

jjmerelo


2 Answers

So these coloned variables are creating a key-value pair.

No, .kv (or kv) is producing the key-value pair:

my $foo = 3;
say kv $foo # (0 3)
like image 155
raiph Avatar answered Sep 18 '22 22:09

raiph


When you call .kv on a list you get a list of indexes each followed by the associated value.

And every singular value will be treated as a list containing one value when you call a listy method on it.


Basically these are the same:

$foo:bar.kv
$foo:bar.list.kv
like image 37
Brad Gilbert Avatar answered Sep 20 '22 22:09

Brad Gilbert