develooper Front page | perl.perl5.porters | Postings from May 2000

Re: Proposed pragma: readonly - summary

Mark Summerfield
May 21, 2000 10:16
Re: Proposed pragma: readonly - summary
Message ID:
Several people have developed independent solutions to readonly
variables which suggests to me that there is a requirement for them:

Andreas pointed out Graham Barr's tie-based solution at

Mark-Jason Dominus pointed out his tie-based solution at

I pointed out my (old) tie-based solution (on my perl antiques page).

The constant pragma doesn't create readonly variables but rather
subroutines which can often be used as readonly's, but I generally want
real readonly scalars.

Tom Christiansen provided XS code for the Const module which can mark
scalars readonly.

I am not keen on any of the tie solutions because for me constants
should be fast and the tie mechanism seems an excessive overhead to get
at unchanging values.

The XS code that Tom gave appears to do the job, but it is runtime and
means that to declare a readonly you have to do it in two steps:

	use Const ;
	use vars qw( $MYREADONLY ) ; # Declare
	const $MYREADONLY = 99 ;     # Set r/o

My proposed pragma declares & sets in one step:

	use readonly '$MYREADONLY' => 99 ;

and this happens at compile time. Also its pure perl.

Is it a big deal doing it in two steps? What if you have a hundred or so
readonlys - writing them all out twice (once for use vars, once for the
const call) isn't difficult but doesn't appeal to me.

I did like the fact that const could be applied at runtime and have
updated so that it too can do this when its needed, but it
takes 3 steps -- I could have done it in two steps... see the sad

Another approach would have been to incorporate the Const XS code into
the readonly pragma, but that would lead to a different syntax (and
would not be pure perl) and the conclusion made it seem pointless:

	use readonly () ;
	use vars qw( $MYREADONLY ) ; # Must declare if run-time
	readonly->set( $MYREADONLY = 99 ) ; 

My sad conclusion is this:

	const $READONLY = 99 ; # OR use readonly '$READONLY' => 99 ;
	*MYREADONLY = \'splat!' ;
	print $READONLY ; # Yep, prints "splat!" and no warnings

Looks like you can't have genuinely readonly scalars in perl unless you
use ties...

Maybe we should have

	my $READONLY : readonly = 'Initialised' ;

as Barrie Slaymaker suggested after all?

Unfortunately I couldn't implement it, I've only just had my first go at
Mark Summerfield Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About