17. Scope and 'my'

On this website, you'll see the keyword 'my' not often. However, you should use it in production code!

the 'my' keyword is used to declare a lexical variable within a limited scope. When you declare a variable with my, it exists only within the block in which it is declared, including any nested blocks. This ensures that the variable does not interfere with similarly named variables outside of its scope. One uses also the terms global and private variables. The example from chapter 12 again:
# 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
Another example:
$x = 10;# $x is a global variable
{
  my $x = 200;# $x is a private variable
  print($x,"\n");# prints 200
}
print($x,"\n");# prints 10
The iterator in for and foreach and the test conditions in while and if structures can be declared as private to the block with the keyword 'my'. When the block ends, variables that are private to that block, are destroyed.
@abc = qw(a b c);
foreach my $item (@abc) {
  print("$item\n");# $item is only visible in this block
}
@lines = <DATA>;
foreach my $line (@lines) {# $line is only visible in this block
 print(uc($line));
}

__DATA__
line1
line2
line3
line4
The pragma use strict; at the top of each perl file ensures you to declare your variables with -what is in most cases sufficient- keyword 'my' before using them (a pragma is a directive that affects the compiler).

Declaring multiple variables is easy:
my($a, $b, $c) = (10, 20, 30);
my($a, $b, $c) = @_;