hankache / rakuguide

The Raku Guide

Home Page:https://raku.guide

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Constants can be lexically scoped in Raku

gitjeff2 opened this issue · comments

In ncitest.raku a constant is defined like this:

constant LIBPATH = "$*CWD/ncitest";

That's entirely valid. However, it really is worth noting to the reader that in Raku, unlike Perl, constants can be lexically scoped with my just like a variable. Thus, the following works as you'd expect:

my constant $A="bar";    
    
sub foo {    
    my constant $A="foo";    
    say $A;    
}    
     
foo();    
say $A;    

The result is:

$ ./constant.raku 
foo
bar

Inside of scopes where $A is already defined as a constant attempts to redefine $A will produce an error. It's worth mentioning this near ncitest.raku, where the first use of constants occurs in the guide. Given the importance of read-only variables to Functional Programming, it's worth reiterating in that section too.