Stories
Slash Boxes
Comments

All the Perl that's Practical to Extract and Report

use Perl Log In

Log In

[ Create a new account ]

Ovid (2709)

Ovid
  (email not shown publicly)
http://publius-ovidius.livejournal.com/
AOL IM: ovidperl (Add Buddy, Send Message)

Stuff with the Perl Foundation. A couple of patches in the Perl core. A few CPAN modules. That about sums it up.

Journal of Ovid (2709)

Tuesday August 30, 2005
03:13 PM

"use constant" versus ReadOnly

[ #26512 ]

I just blew a nice chunk of time debugging the following problem:

use constant DEFAULT_ARGS => [qw/some data/];

...

unless (@_) {
    $self->{args} = DEFAULT_ARGS;
}

Later on in my code, I had this:

my $args = $self->args;
while ( defined (my $curr_arg = shift @$args) ) {
    # do something while blithely ignoring
    # the havoc we're wreaking
}

See the bug? The two accidentally coupled lines of code were 214 lines apart and appeared to be unrelated. That was a bugger to track down. The fix I used was to simple clone those args when needed, but my longer-term fix is to not use constants. Use ReadOnly:

#!/usr/bin/perl

use strict;
use warnings;
use Data::Dumper::Simple;
use ReadOnly;

use constant FOO => [qw/bar baz/];
my $data = FOO;
shift @$data;
print Dumper(FOO);

Readonly::Scalar my $foo => [qw/bar baz/];
$data = $foo;
shift @$data;
print Dumper($foo);

And the output:

$FOO = [
  'baz'
];
Modification of a read-only value attempted at constant.pl line 15

The Fine Print: The following comments are owned by whoever posted them. We are not responsible for them in any way.
 Full
 Abbreviated
 Hidden
More | Login | Reply
Loading... please wait.