SPUG:Object property question
Michael R. Wolf
MichaelRunningWolf at att.net
Fri May 2 01:58:07 CDT 2003
Jeremy Kahn <kahn at cpan.org> writes:
[...]
Just a flourish or two that may (or may not) be interesting to folks,
depending on the situation.
{
my $serial_id = 100_000;
sub init_newMember {
my $this = shift;
$this{FirstName} = shift || "<unknown>";
$this{LastName} = shift || "<unknown>" ;
$this{id} = shift || $serial_id++;
}
}
Two tricks here:
0 -- reorder the arguments so that a 2-argument call will default the
ID to a serially incrementing number starting at 100,000.
1 -- create a "static" variable lexically scoped to the function
only. Increment it for each call. Note the "extra" block to protect
the variable from outside visibility, but still allow it inside the
function, but that it's outside the function so that it gets
initialized once and retains its value across calls. (NB -- untested
code. Does anyone know if the initialization happens as I expect, or
does it require a BEGIN block?)
{
my $serial_id;
BEGIN {$serial_id = 100_000;}
sub init_newMember {....}
}
2 -- take advantage of the short-circuit 'or' operator to set
defaults.
[...]
> This is all *very* powerful, and kinda hacked together. I strongly
> recommend The Damian's book "Object Oriented Perl" -- the first five
> or six chapters are a great introduction to this subject.
Hear, hear!!!!
Michael
P.S. Nicely explained, Jeremy.
--
Michael R. Wolf
All mammals learn by playing!
MichaelRunningWolf at att.net
More information about the spug-list
mailing list