Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: A few random questions from Learning Perl 3

by blokhead (Monsignor)
on Jan 06, 2003 at 04:52 UTC ( #224542=note: print w/replies, xml ) Need Help??


in reply to A few random questions from Learning Perl 3

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

Replies are listed 'Best First'.
Re: Re: A few random questions from Learning Perl 3
by Hofmator (Curate) on Jan 06, 2003 at 09:40 UTC

    Just as a sidenote, this

    my $whole_file; { local($/) = undef; $whole_file = <F>; # <> operator reads in all of the data from fil +ehandle F }
    could also be written more concisely like this:
    my $whole_file = do { local $/; <F> };

    -- Hofmator

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://224542]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (10)
As of 2020-02-18 16:04 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    What numbers are you going to focus on primarily in 2020?










    Results (76 votes). Check out past polls.

    Notices?