On Mon, Mar 16, 2009 at 11:16, Suzanne Aardema <[email protected]> wrote:
snip
> I do this regularly redefine constants in my programs. I'm not sure if it's
> good practice but I do it.
>
> What I do is define a constant in most subroutines. The constant is called,
> strange enough, PROC_NM. I felt that because this was being defined local to
> each routine that I wasn't breaking all the rules I had been taught. I know I
> get a warning message each time I redefine it but to me it is a local
> constant not a variable. I don't define it in my helper routines so when they
> printout an error message and reference PROC_NM I know where they are called
> from.
>
> If anyone has a better idea I'd love to hear it.
snip
It sounds like you need Readonly::XS[1]. The constant pragma creates
constants by writing a subroutine like
sub PI() { 3.14 }
Subroutines are global in scope, so it doesn't matter that you are
using the constant only in one function. Readonly::XS creates
constants by turning on a bit in the scalar that makes the variable
read only (hence its name). Since this is a normal scalar, it can
have the scope you desire for it. The Readonly[2] module also allows
you to create read only hashes and arrays (at the cost of some speed).
#!/usr/bin/perl
use strict;
use warnings;
use Readonly;
func1();
func2();
sub func1 {
Readonly my $PROC_NM => (caller 0)[3];
print "I am in $PROC_NM\n";
}
sub func2 {
Readonly my $PROC_NM => (caller 0)[3];
print "I am in $PROC_NM\n";
}
1. http://search.cpan.org/dist/Readonly-XS/XS.pm
2. http://search.cpan.org/dist/Readonly/Readonly.pm
--
Chas. Owens
wonkden.net
The most important skill a programmer can have is the ability to read.
--
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
http://learn.perl.org/