There are many uses for naked blocks, but one common way is for restricting access to lexical variables. Declare them inside the block and they are inaccessible (by name) outside the block. Their
values can still exist in memory if there are references to them.
{
my $counter = 0;
sub inc_counter { $counter++ }; # $counter is visible here
sub get_counter { $counter }; # and here
}
The
$counter variable has gone out of scope at the end of the block, therefore, you can never directly modify its value explicitly. However, since references to the variable are still made (in the two subroutines), the
$counter variable's value still exists. It can only be accessed through these subs, however. But no one code can (maliciously) say
$counter = -100, for example. This type of construction is called a closure, BTW.
Naked blocks are also convenient for setting temporary values to globals:
$/ = "\n";
my $line = <STDIN>; # <> operator reads just one line
my $whole_file;
{
local($/) = undef;
$whole_file = <F>; # <> operator reads in all of the data from fi
+lehandle F
}
$line = <STDIN>; # reads just one line again, since $/ returns
+to "\n"
As for the next keyword, sure it can be used twice or more inside a looping block:
for (0 .. 100) {
next unless $_ % 2; # skip multiples of 2
next unless $_ % 5; # skip multiples of 5
print "$_\n";
}
This prints all numbers that aren't divisible by 2 or 5. You can code
next many times in your block, but of course only one of them can be
followed per iteration.
next does not skip you automatically to the 100th iteration of this loop, just the next one. Try it out!
blokhead