develooper Front page | perl.perl5.porters | Postings from August 2014

Re: How about having a recommended way to add constant subs dynamically?

Thread Previous | Thread Next
From:
Father Chrysostomos
Date:
August 21, 2014 04:49
Subject:
Re: How about having a recommended way to add constant subs dynamically?
Message ID:
20140821044934.29399.qmail@lists-nntp.develooper.com
Avar wrote, though not in this order:
>
> What do you think, Father Chrysostomos?

I was hibernating (or vernating) when this whole issue arose, so I am
very late to the discussion.

> Anyway, for how to define real constants without constant.pm you need
> look no further than the source for constant.pm itself, notice how it
> defines the _CAN_PCS constant. After 5.9.2 this trick works:
> 
> BEGIN {
>     my $const = "blah";
>     $main::{CONSTANT} = \$const;
> }

No, please don't go that way!  Such stash manipulation is explicitly
documented as subject to change in behaviour.  And it has changed more
than once in recent years.

> > diff --git a/dist/constant/lib/constant.pm b/dist/constant/lib/constant.pm
> > +sub define_in {
> 
> I'd welcome a patch like that, I thought of submitting one before,
> which would be a slightly different one to support:
> 
>     use constant {
>         "some::package" => 1,
>         "other::package" => 2,
>     };
> 
> It would accomplish the same thing, be backwards compatible because
> "::" in constant names isn't allowed now, and you could quickly define
> constants in multiple packages in one call, but I don't know if anyone
> cares about that.

I lean toward the latter, but I don't really mind.  People can already
use constant->import to create constants dynamically, so why change
that?  Just extend it.

> In any case I think we should actively track down CPAN modules that
> use the "sub () { $var }" idiom and file bugs against them, they're
> now behaving differently than their authors intended.

That's a good idea.  Would a grep be sufficient?

> How about warning for constant subs that have a "()" signature and one
> variable as the whole body? This has been a well known idiom to define
> constants for so long that I can see bugs cropping up in various CPAN
> and darkPAN code because of it.

The problem with a warning like that is that most code that does
sub (){$var} will not actually modify the $var after creating the
closure, so it will continue to behave exactly the same way.  Hence,
the warning seems excessive.  We're saying, not that the behaviour
will change, but that the implementation will change and it will
be slower.

Since the change that was backed out probably broke nothing (in terms
of behaviour, as opposed to efficiency), submitting patches to CPAN
modules is sufficient, I think.


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