Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected FAIL with :exists in raku

While trying to debug program code I ran into the following:

(base) hsmyers@BigIron:~$ rlwrap -A raku

To exit type 'exit' or '^D'
> my regex N { <[A..G]> };
regex N { <[A..G]> }
> my %h = A => 1, B => 2;
{A => 1, B => 2}
> 'B' ∈ %h.keys
True
> my $m = 'B' ~~ / <N> /;
「B」
 N => 「B」
> $m ∈ %h.keys
False
> $m.Str ∈ %h.keys
True
> my $n = $m.Str
B
> $n ∈ %h.keys
True
> %h<B>:exists
True
> %h<$n>:exists
False
>

In sum the question is how do you go from match object to string such that %whatever:exists will work. 'Element of keys' provides a workaround, but I believe that is not the correct way to check for key existence?

like image 337
hsmyers Avatar asked Mar 02 '20 19:03

hsmyers


2 Answers

<a b c> is a shortcut for qw<a b c>.
Which will end up as 'a', 'b', 'c'

The way to access a Hash by key is with {}

%h{'a', 'b', 'c'}

Which would be nicer to write as:

%h{<a b c>}

What would be even nicer is to get rid of the {}

%h<a b c>

That is why that is valid Raku syntax.

So when you write this:

%h<$n>

It is basically the same as:

%h{'$n'}

If you are accessing only one element, and it has no whitespace.
Rather than doing this all of the time:

%h{'abc'}

It is much simpler to just use:

%h<abc>

Which is why all of the documentation uses that form.


Similarly these are also the same:

$/{<a b c>}
$/<a b c>
$<a b c>

So if you see $<abc> it is really looking inside of $/ for the value associate with the key abc.

There is a lot of syntax reuse in Raku. <> is one such case.


Note:

You don't need to use .keys on a Hash with .

'B'  ∈  %h;   # True

(Since Raku uses different operators for different operations, it is rare that you would have to do such data massaging.)

like image 81
Brad Gilbert Avatar answered Oct 22 '22 22:10

Brad Gilbert


You put matches in Str context by using ~, but I think the problem is your case is that you're using literal quotes <> for a variable. %h<$n> returns the value corresponding to the literal key $n. You need to use %h{$n} to retrieve the value corresponding to the content of $n. Also, if $n contains a Match it will be put in Str context, so that should work.

like image 26
jjmerelo Avatar answered Oct 22 '22 21:10

jjmerelo