Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a constants value as a hash key

Tags:

raku

Is there a simple way to use the value of a defined constant as a hash / pair key in Perl6?

For instance :

constant KEY = "a string";
my %h = ( KEY => "a value" );

This will creatre a key of "KEY" not "a string".

I can do :

my %h = ( "{KEY}" => "a value" );

But that seems a bit clunky. I was wondering if there was a better way?

like image 442
Scimon Proctor Avatar asked Sep 14 '18 09:09

Scimon Proctor


1 Answers

The most convenient options would be to either:

  • Declare the constant with a sigil (such as constant $KEY = "a string";), thus avoiding the problem in the first place
  • Wrap the left hand side in parentheses (like (KEY) => "a value"), so it won't be treated as a literal
  • Write it instead as pair(KEY, "a value")

Also, note that:

my %h = ( "{KEY}" => "a value" );

Is a useless use of parentheses, and that:

my %h = KEY, "a value";

Will also work, since non-Pairs in the list of values to assign to the hash will be paired up. It loses the visual pairing, however, so one of the previously suggested options is perhaps better.

like image 70
Jonathan Worthington Avatar answered Sep 17 '22 19:09

Jonathan Worthington