[Edinburgh-pm] code style question

Aaron Crane perl at aaroncrane.co.uk
Wed Aug 17 07:39:55 PDT 2011


Alex Brelsfoard <alex.brelsfoard at gmail.com> wrote:
> I just came across some code that used some old-style coding practice, and I
> wanted to know if there was still any GOOD reason for using it:
>
> The code I saw was referencing variables using the $:: pragma:

It's just fully-qualified name syntax, not a pragma.

As others have noted, the empty-named package is an alias for the
`main` package:

$ perl -E 'say *main::x{PACKAGE}'
main
$ perl -E 'say *::x{PACKAGE}'
main

> $::var

I've occasionally used this for (uncommitted!) temporary debugging
code — do `$::n++` in the middle of some module's code, then other
packages can easily check how many times that line was invoked.  But
I've never seen any need for it in real code, and it has all the
problems that package variables always do.

> To my understanding this is a bit messy, and not to mention potentially
> dangerous as it kinda goes against the "use strict;" methodology, does it
> not?

Sort of; the usual intention of `use strict` (or, more specifically,
`use strict qw<vars>`) is to say you want your variables to be
lexically scoped.  But it's entirely deliberate that the variables
stricture allows you to use package variables as long as you fully
qualify their names; `perldoc strict` says that it "generates a
compile‐time error if you access a variable that wasn't declared via
C<our> or C<use vars>, localized via C<my()>, or wasn't fully
qualified."  (That description omits mention of `state`, though.
*Makes note to file documentation bug.*)

-- 
Aaron Crane ** http://aaroncrane.co.uk/


More information about the Edinburgh-pm mailing list