Consider creating shared $aa
and $bb
variables inside a lexical closure to generate new cob hashes.
sub make_cob {
my($aa,$bb) = (0, 0);
{ a => \$aa,
b => \$bb,
z => sub { $aa + $bb + 1 },
};
}
The variable names $aa
and $bb
avoid a warning in the perlvar documentation on $a
and $b
in case you ever need to perform any sorting in make_cob
:
$a
$b
Special package variables when using sort. Because of this specialness $a
and $b
don’t need to be declared (using use vars
, or our
) even when using the strict 'vars'
pragma. Don’t lexicalize them with my $a
or my $b
if you want to be able to use them in the sort comparison block or function.
Using one as a plain hash %cob
looks like
my %cob = %{ make_cob() };
${$cob{a}} = 10;
${$cob{b}} = 20;
print "z: ", $cob{z}(), "\n";
As a hash reference $cob
, the code is
my $cob = make_cob;
${$cob->{a}} = 30;
${$cob->{b}} = 40;
print "z: ", $cob->{z}(), "\n";
You might wrap them all in anonymous subs, as in
sub make_cob {
my($aa,$bb) = (0, 0);
{ a => sub { if (@_) { $aa = shift } else { $aa } },
b => sub { if (@_) { $bb = shift } else { $bb } },
z => sub { $aa + $bb + 1 },
};
}
my $cob = make_cob;
$cob->{a}(40);
$cob->{b}(50);
print "a: ", $cob->{a}(), "\n",
"b: ", $cob->{b}(), "\n",
"z: ", $cob->{z}(), "\n";
But if you are going to all that trouble, make your cobs instances of a Cob class.
package Cob;
use strict;
use warnings;
sub new {
my($class,$aa,$bb) = @_;
$_ = defined $_ ? $_ : 0 for $aa, $bb;
bless { a => $aa, b => $bb } => $class;
}
sub a { $_[0]->{a} }
sub b { $_[0]->{b} }
sub z { $_[0]->a + $_[0]->b + 1 }
1;
Exercise this class with
#! /usr/bin/env perl
use strict;
use warnings;
use Cob;
my $cob = Cob->new(1,2);
print "a: ", $cob->a, "\n",
"b: ", $cob->b, "\n",
"z: ", $cob->z, "\n";
Output:
a: 1
b: 2
z: 4