12. Blocks

12.1 Nested blocks

Nested blocks are used to create scopes for variables and to control the flow of execution within the program. Here's an example demonstrating the use of nested blocks:
# Outer block
{
    my $outer_var = "Outer variable"; # 'my' is necessary to give a variable block scope
    print "Outside nested block: $outer_var\n";

# Inner block
    {
        my $inner_var = "Inner variable"; # 'my' is necessary to give a variable block scope
        print "Inside nested block: $inner_var\n";
    }

# $inner_var is no longer accessible here
}

# $outer_var is no longer accessible here

12.2 BEGIN - END blocks

BEGIN and END blocks are special blocks that allow you to execute code at the beginning and end of the program, respectively. They could be used for e.g. initialization and cleanup tasks. While BEGIN and END blocks can be useful in certain situations, it's important to use them sparingly. So it's generally a good idea to limit their usage to cases where they provide clear benefits in terms of code organization or functionality.
BEGIN {
    print "1st BEGIN block: this is executed before the rest of the program.\n";
}

BEGIN {
    print "2nd BEGIN block: this is executed before the rest of the program.\n";
}

END {
    print "END block: this is executed at the end of the program.\n";
}

print("-" x 55, "\n");
print "Main part of the program.\n";
print("-" x 55, "\n");
Both BEGIN blocks are executed as soon as Perl encounters them during the compilation phase, even before the rest of the script is parsed (that's even true if you put the BEGIN blocks at the end of the code - which makes no sense of course). Conversely, the END block is executed just before the Perl interpreter exits, after the main part of the program has been executed.

If you have initialization code that needs to run conditionally based on certain factors determined at runtime, you might use BEGIN blocks to ensure that the initialization code runs before the rest of the program.
# Condition to determine if we need to perform initialization
$perform_initialization = 1;

# Check if initialization is needed
if ($perform_initialization) {
    BEGIN {
        print "Performing initialization...\n";
        # Initialization code goes here
    }
}

# Main part of the program
print("This is the main part of the program.\n");