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.{ my $counter = 0; sub inc_counter { $counter++ }; # $counter is visible here sub get_counter { $counter }; # and here }
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:
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!for (0 .. 100) { next unless $_ % 2; # skip multiples of 2 next unless $_ % 5; # skip multiples of 5 print "$_\n"; }
blokhead
In reply to Re: A few random questions from Learning Perl 3
by blokhead
in thread A few random questions from Learning Perl 3
by sulfericacid
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |