On 8/28/22 19:11, Bruce Gray wrote:
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
Hi Bruce,
Thank you! I understand now.
I was channeling my old Modula2 days, where
everything had a BEGIN and an END. I did not
realize BEGIN was a "name". A special name
of a subroutine that would run before compile
was complete.
I am now thinking of firing off a call to libnotify
with a delayed close out time to simulate a splash
screen.
Question, would BEGIN go at the top or the bottom
of my code? Seems the compiler would hit it first
at the top, but I do not know if it makes a full
pass of everything before firing off the BEGIN.
-T