http://qs1969.pair.com?node_id=1128600

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.