develooper Front page | perl.perl5.porters | Postings from June 2010

Re: Why are subs matching /^[\W_]$/ global?

Thread Previous | Thread Next
June 2, 2010 06:12
Re: Why are subs matching /^[\W_]$/ global?
Message ID:
On Wed, Jun 02, 2010 at 12:46:44PM +0000, Ævar Arnfjörð Bjarmason wrote:
> Single-character non-alpha (plus _) subroutines are global
>     $ perl -le '** = sub {warn "Hi"}; package Foo; &*'
>     Hi at -e line 1.
>     $ perl -le '*a = sub {warn "Hi"}; package Foo; &a'
>     Undefined subroutine &Foo::a called at -e line 1.
> and:
>     $ perl -le '*_ = sub {warn "Hi"}; package Foo; &_'
>     Hi at -e line 1.
>     $ perl -le '*__ = sub {warn "Hi"}; package Foo; &__'
>     Undefined subroutine &Foo::__ called at -e line 1
> This came up when I was looking at _() in Perl as a potential Gettext
> wrapper (I know about the _ filehandle).
> _ I think I can understand (presumably the _ glob is global). But why
> does this apply generally to all /^[\W_]$/ subs? Is it explicitly
> documented somewhere? Perhaps it's something we'd want to deprecate?

Documented. From perlvar:

       Perl identifiers that begin with digits, control characters, or
       punctuation characters are exempt from the effects of the "package"
       declaration and are always forced to be in package "main"; they are
       also exempt from "strict 'vars'" errors.  A few other names are also
       exempt in these ways:

               ENV             STDIN
               INC             STDOUT
               ARGV            STDERR
               ARGVOUT         _

       In particular, the new special "${^_XYZ}" variables are always taken to
       be in package "main", regardless of any "package" declarations
       presently in scope.

Note also that perlvar claims all such names are reserved for special uses
by Perl. From the same manual page:

       Perl variable names may also be a sequence of digits or a single
       punctuation or control character.  These names are all reserved for
       special uses by Perl; for example, the all-digits names are used to
       hold data captured by backreferences after a regular expression match.
       Perl has a special syntax for the single-control-character names: It
       understands "^X" (caret "X") to mean the control-"X" character.  For
       example, the notation $^W (dollar-sign caret "W") is the scalar
       variable whose name is the single character control-"W".  This is
       better than typing a literal control-"W" into your program.

Basically, it comes down to, "if it global, you can't have it anyway".


Thread Previous | Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About