Using a variable in a Perl 6 program before assigning it

I want to assign literals to some of the variables at the end of the file by my program, but to use these variables earlier. The only method I came up with for this is this:

my $text;

say $text;

BEGIN {    
    $text = "abc";
}

Is there a better / more idiomatic way?

+4
source share
3 answers

Just do some work.

Instead, create routines:

say text();

sub text { "abc" }


UPDATE (thanks raiph! Including your feedback, including a link to term:<>):

In the above code, I initially omitted the parentheses for the call text, but it would be more convenient to maintain so that they always include them, to prevent parsing a misunderstanding of our intent. For instance,

say text();          # "abc" 
say text() ~ text(); # "abcabc"
say text;            # "abc", interpreted as: say text()
say text ~ text;     # ERROR, interpreted as: say text(~text())

sub text { "abc" };

, text a term, , text , text():

say text;        # "abc",    interpreted as: say text() 
say text ~ text; # "abcabc", interpreted as: say text() ~ text()

sub term:<text> { "abc" };

pure trait ( !). is pure , " - " :

say text;        # "abc",    interpreted as: say text() 
say text ~ text; # "abcabc", interpreted as: say text() ~ text()

sub term:<text> is pure { "abc" };
+5

Perl 5, Perl 6 a BEGIN . , , , BEGIN say.

BEGIN my $text = "abc";
say $text;

, .

+3

-, :

( ..), ?

Autodeclare

strict "pragma" , , P6, /, sigil, .

P6 . , , / , my. , , P6 , /.

use strict no strict, :

no strict;

say $text;

BEGIN {    
    $text = "abc";
}

no strict , use strict .

,

. :

say my $text;

BEGIN {    
    $text = "abc";
}

my $bar , . , say my $bar = 42; if foo { say my $bar = 99 } $bar .

BEGIN .

/ , INIT:

say my $text;

INIT {    
    $text = "abc";
}

A PS ?

, - Perl 6 () / Rakudo (), - "". ( P6/Rakudo , - P6, P6 MOP, P6 pragmas.)

, - - :

use PS;

say $text;

BEGIN $text = 'abc';

$text mainline , no strict. PS , / , / , ( ).

say foo;
sub foo { 'abc' }

, , .

(More precisely, when the P6 compiler encounters an identifier without sigil while parsing some source code, it checks if it has already seen the declaration of this identifier. If it does not matter, then it assumes that the identifier corresponds to the procedure that will be announced later and will be move on. If his assumption is wrong, it will not compile.)

You can use routines as if they were variables, as described in Christopher Bott's Answer .

+3
source

Source: https://habr.com/ru/post/1694653/


All Articles