> On Aug 28, 2022, at 5:58 PM, ToddAndMargo via perl6-users 
> <perl6-us...@perl.org> wrote:
> 
> Hi All,
> 
> I am thinking of using
> 
>   BEGIN {}
> 
> to fire up a splash screen (libnotify).
> 
> Question: is what happens between the brackets
> isolated from the rest of the code?   If I set
> variable values or declare variables, are they
> wiped out, etc.?
> 
> Many thanks,
> -T

BEGIN blocks create a lexical scope, because they are *blocks*, so any 
variables that you declare within the block don't exist outside the block.

Variables that you define in the lexical scope *surrounding* the BEGIN block 
can have their values set inside the BEGIN block, and those values will be 
retained after BEGIN ends. 

my $a_var;
sub do_something ( ) {
    say "did something! By the way: ", (:$a_var), ' inside a sub called from 
the BEGIN block, because the var is shared between them (same lexical scope).';
}
BEGIN {
    $a_var = 42;
    my $b_var = 11;
    say "a_var is $a_var within the BEGIN block";
    say "b_var is $b_var within the BEGIN block";
    do_something();
}
say "a_var is still $a_var outside the BEGIN block";
# say "b_var is still $b_var outside the BEGIN block"; # Commented out, because 
illegal!

Output:
a_var is 42 within the BEGIN block
b_var is 11 within the BEGIN block
did something! By the way: a_var => 42 inside a sub called from the BEGIN 
block, because the var is shared between them (same lexical scope).
a_var is still 42 outside the BEGIN block

-- 
Hope this helps,
Bruce Gray (Util of PerlMonks)

Reply via email to