perlquestion
aufrank
<p>hey all--</p>
<p>I'm working on a method in my first OO project which seems like it should be simple but ended up pretty complex (and still doesn't DWIW). The idea is that I only want to allow certain values to be passed as parameters, and I want to assign a default if the value passed is not one of the legal ones. Here my attempted WTDI:</p>
<code>#! perl -w
use strict;
package Test;
sub new {
my $class = $_[0];
my $self = {'associations' => undef,
'balance_by' => undef,
'comment' => undef};
bless $self, $class;
return $self;
}
sub balance_by {
my $self = shift;
my $entry = shift;
my %valid_params = map {$_ => 1} ('foo',
'bar');
unless (defined $self->{'balance_by'}) {
$self->{'balance_by'} =
(defined $entry && $valid_params{$entry})
? $entry
: 'foo';
}
return $self->{'balance_by'};
}
my $lex = Test->new();
$lex->balance_by('bar');
print $lex->balance_by();
</code>
<p>initially this seemed to work fine, but when I went back and added the line
<code>
print $lex->balance_by('baz')
</code>
it still prints "bar". I realize now that the way I used the <code>unless</code> loop makes it impossible to update the value once it has been defined once, but I am at a loss. How should I go about doing this?</p>
<p>thanks in advance,<br />
--au</p>
<p><small>this was going to be a question about lists, arrays, <code>$_</code>, <code>@_</code>, and <code>shift</code>, but an excellent CB discussion unmuddied my head a bit (or at least showed me that the subject is inherently muddy ;-)</small></p>