Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Why to wrap Perl classes inside a Perl script into blocks

by capfan (Sexton)
on Jun 01, 2015 at 16:50 UTC ( [id://1128600]=perlquestion: print w/replies, xml ) Need Help??

capfan has asked for the wisdom of the Perl Monks concerning the following question:

Dear all,

I just had a look at the script here: http://www.perlmonks.org/?node_id=1023430.
In the Perl script, all Perl classes are wrapped in a code block.

Why?

I'd guess it's to make sure that the scopes don't mix. But isn't this already done by using another name space?

Thanks all

  • Comment on Why to wrap Perl classes inside a Perl script into blocks

Replies are listed 'Best First'.
Re: Why to wrap Perl classes inside a Perl script into blocks
by herveus (Prior) on Jun 01, 2015 at 17:03 UTC
    Howdy!

    You're on the right track. However, lexical variables' scope is delimited by the blocks. package does not make a new scope.

    Consider:

    { package Foo; my $foo; } { package Bar; my $foo; # new $foo not to be confused with one above }

    Versus:

    package Foo; my $foo; package Bar; my $foo; # my declaration masks previous one

    yours,
    Michael
Re: Why to wrap Perl classes inside a Perl script into blocks
by Eily (Monsignor) on Jun 01, 2015 at 17:05 UTC

    I'd guess it's to make sure that the scopes don't mix
    Yup, good answer. Most of the time you'll have only one namespace, or package in each file, so each namespace is scoped to the file. Here this syntax is used to emulate the multi-file scoping in a more compact and easy to test way.

    But isn't this already done by using another name space?
    Only with the package ... BLOCK syntax, (which appeared in perl v5.14). Compare:
    package First; our $var = 1; package Second; $var++; print $First::var;
    with
    package First { our $var = 1; } package Second { $var++; #doesn't work under strict print $First::var; }
    The syntax in this post can be used if you want to be compatible with older versions of perl.

Re: Why to wrap Perl classes inside a Perl script into blocks
by hippo (Bishop) on Jun 01, 2015 at 17:07 UTC

    Without the braces the very last line would be part of package Calc. The braces are indeed there to limit the scope of the packages as without them there is no equivalent to an "end package" statement.

A reply falls below the community's threshold of quality. You may see it by logging in.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1128600]
Approved by herveus
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (2)
As of 2024-04-16 20:36 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found