Title: RE: defining 'constants' at run time

david nicol wrote on 11 March 2004 18:38:
> On Thu, 2004-03-11 at 05:20, Orton, Yves wrote:
>
> > use constant ARG1=>$ARGV[0];
> >
> > is better
>
> Absolutely.  the begin block posting was a hurried and untested
> example of how to use a BEGIN block.

For the record I threw that in for other readers, not so much yourself.

:-)

> By the time people subscribe
> to module-authors you'd think they would know how to use a BEGIN
> block to evalueate some parts of their program before the rest of
> it. 

Youre expecting them to have read the fine manual? Yikes! ;-)

> I suspect that since @ARGV is set before any compiling happens,
> a bign block might not actually be needed in that case at all.

Nope i dont think it is. And a useful thing to remember is that

  use Foo @args;

is really a special way to spell

  BEGIN { require Foo; Foo->import(@args) }

so

  use constant ARG1=>$ARGV[0];

is equivelent to

  BEGIN { require constant; constant->import(ARG1=>$ARGV[0]); }

which is more or less equivelent to

  BEGIN { eval 'sub ARG1 () { $ARGV[0] }' }

This is actually a useful trick as you can do tricky stuff inside of the implied BEGIN that a use represents.

> A better example would have had a complex startup phase entirely
> within the BEGIN block, and the last thing in the BEGIN block is,
> to establish the 'constants' through whatever mechanism is
> appropriate,
> such as reading the rest of the source code through a source filter
> that replaces the 'constants' with their values, in single quotes,
> rather than making Perl compile and optimize. 

Is it actually better to do it that way really? I would have thought the eval as you go _expression_ simplification would do the same thing but more efficiently than a source filter ever could.

Having said that ive used something very close to this approach in Tie::Array::PackedC as well as in a few other places like http://perlmonks.org/index.pl?node_id=289585 (although the latter has problems due to use base qw// not playing nicely with evaled packages that have no %INC entry.)

> For that matter, the
> source filter could output ANSI C and pass it to yor
> compiler.  Somebody
> give me a grant!


Yeah, thats the ticket. Sombody give him a grant. I wanna get me some o that action fer sure.

:-)

Yves

Reply via email to