in reply to Syntax for preventing repeat object initializations

Funnily enough, {__PACKAGE__} could just as well be {__gobbledegook__}. The __PACKAGE__ compile-time token doesn't get substituted with its actual value if it appears to the left of => or inside braces.

_____________________________________________________
Jeff japhy Pinyan: Perl, regex, and perl hacker.
s++=END;++y(;-P)}y js++=;shajsj<++y(p-q)}?print:??;

  • Comment on Re: Syntax for preventing repeat object initializations

Replies are listed 'Best First'.
(Ovid) Re(2): Syntax for preventing repeat object initializations
by Ovid (Cardinal) on Jul 17, 2001 at 04:17 UTC

    Very interesting. I created the following package:

    package Scrap::Foo; use strict; sub bar { my $dummy; $dummy->{_init}->{__PACKAGE__}++; return $dummy; } 1

    And my test code:

    use strict; use Scrap::Foo; use Data::Dumper; my $dummy = Scrap::Foo::bar(); print Dumper $dummy;

    Generated this output:

    $VAR1 = { '_init' => { '__PACKAGE__' => '1' } };

    And the fix:

    my $package = __PACKAGE__; $dummy->{_init}->{$package}++;

    Thanks for the info. Now who wants to tell Damian? :)

    Cheers,
    Ovid

    Update: japhy's unary fix is not only shorter, but it should be faster as it doesn't involve creating a variable for no other reason than throwing it away.

    Vote for paco!

    Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.

      The "unary +" fix is shorter...
      $foo->{+__PACKAGE__} = 1;
      Hmm, patching a book isn't quite so easy!

      _____________________________________________________
      Jeff japhy Pinyan: Perl, regex, and perl hacker.
      s++=END;++y(;-P)}y js++=;shajsj<++y(p-q)}?print:??;

        I was toying around with __PACKAGE__ just yesterday. For interpolation into strings, you can do the scalar ref-deref trick:
        my $str = "I'm in package ${\__PACKAGE__}"
           MeowChow                                   
                       s aamecha.s a..a\u$&owag.print