hankache / rakuguide

The Raku Guide
https://raku.guide
Creative Commons Attribution Share Alike 4.0 International
194 stars 65 forks source link

Constants can be lexically scoped in Raku #220

Open gitjeff2 opened 3 years ago

gitjeff2 commented 3 years ago

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.