[Wellington-pm] 'enum' for Perl?
Cliff Pratt
enkidu at cliffp.com
Mon Apr 17 00:33:25 PDT 2006
Grant McLean wrote:
> On Mon, 2006-04-17 at 12:36 +1200, Cliff Pratt wrote:
>
>>Cliff Pratt wrote:
>
> ...
>
>>>I can see how that works, but some modules export what appear to be
>>>variables, eg
>>>
>>>use Glib qw(TRUE FALSE) ;
>>>
>>>and you can then say, eg
>>>
>>>my $debug = FALSE ;
>>>
>>>Or is FALSE just a hidden subroutine that sets the return to the
>>>appropriate value?
>>>
>>
>>To answer my question, Glib uses the Exporter module and 'use constant'.
>>I don't yet understand *what* it is doing exactly, but that is what is
>>*does* do. <grin>
>
>
> Good detective work :-)
>
> If you care how it works, this ...
>
> use constant TRUE => 1;
>
> ... is actually translated to this ...
>
> sub TRUE() { return 1; }
>
> The Exporter module can alias a subroutine or a variable from one
> namespace (eg: Glib::TRUE) to another (eg: main::TRUE). Which allows
> you to call the subroutine as if you had defined it in your own code.
>
> One non-obvious twist is that the subroutine was declared like this:
>
> sub TRUE() { return 1; }
>
> rather than this:
>
> sub TRUE { return 1; }
>
> The significance of the empty trailing parentheses after the subroutine
> name is that it's a prototype which declares that the subroutine takes
> no arguments. Once Perl has compiled your script (and all the modules
> it includes) into an in-memory opcode tree, it does an optimisation pass
> through the opcodes. One of the things it does during this pass is to
> 'inline' the constants by replacing all calls to subroutines which
> return a literal value and are prototyped to take no arguments, with the
> literal values themselves. Thus, at run-time, the TRUE subroutine is
> never actually called.
>
> Sorry you asked? :-)
>
No, it's interesting! I'm quite pleased that my guess/deduction that
'FALSE' is a subroutine that returns the appropriate value was on target!
Cheers,
Cliff
--
http://barzoomian.blogspot.com
More information about the Wellington-pm
mailing list