develooper Front page | perl.perl5.porters | Postings from July 2013

Re: [perl #118701] __PACKAGE__ does not work as a hash key

Thread Previous | Thread Next
From:
Brad Gilbert
Date:
July 2, 2013 05:44
Subject:
Re: [perl #118701] __PACKAGE__ does not work as a hash key
Message ID:
CAD2L-T1VtjX94FWrEgLW3AOkEc-Xa0P2xhQd3kAEOGR=KcniBg@mail.gmail.com
On Mon, Jul 1, 2013 at 10:46 PM, Lukas Mai <plokinom@gmail.com> wrote:
> On 02.07.2013 00:42, Jim Avera wrote:
>>
>> On 06/30/2013 05:06 AM, James E Keenan via RT wrote:
>>>
>>> This limitation has been documented in 'perlmod' since 1997: ##### The
>>> special symbol C<__PACKAGE__> contains the current package, but cannot
>>> (easily) be used to construct variable names. ##### Is there any
>>> compelling reason why we should alter this long-standing behavior?
>
>
> Wrong part of the documentation. The above only means you can't say
> $__PACKAGE__::foo or similar. Jim isn't trying to construct a variable name.
>
>
>> At this point in Perl's history not much is really compelling, so I
>> guess the answer is no.
>>
>> But still, perldata says __PACKAGE__ etc. are "special literals" which
>> may (only) be used as "separate tokens".  That makes it sound like they
>> are recognized while scanning regardless of the context.
>>
>> I found this the hard way (i.e. as a silent bug) when $hash{__PACKAGE__}
>> interpreted __PACKAGE__ as a bareword or unquoted string, rather than as
>> a special literal token.  It's another "hidden gotcha" which would be
>> nice to eliminate.
>
>
> As Father Chrysostomos explained, hash keys always autoquote identifiers.
> Special-casing __PACKAGE__ would introduce another hidden gotcha, not
> eliminate it.
>

If you need the special literal there are a few easy ways to do it

    perl -E'%h=(main=>"Hello World"); say $h{+ __PACKAGE__ }'
    perl -E'%h=(main=>"Hello World"); say $h{ __PACKAGE__, }'
    perl -E'%h=(main=>"Hello World"); say $h{ ( __PACKAGE__ ) }'
    perl -E'%h=(main=>"Hello World"); say $h{ do{ __PACKAGE__ } }'

basically anything that tells perl (the compiler) that you want
it treated as a statement will work.

on 5.16 or later you can also pretend it is a subroutine
    perl -E'%h=(main=>"Hello World"); say $h{ __PACKAGE__() }'

Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About