Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

hey all--

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:

#! 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();

initially this seemed to work fine, but when I went back and added the line

print $lex->balance_by('baz')
it still prints "bar". I realize now that the way I used the unless 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?

thanks in advance,
--au

this was going to be a question about lists, arrays, $_, @_, and shift, but an excellent CB discussion unmuddied my head a bit (or at least showed me that the subject is inherently muddy ;-)


In reply to only allow certain parameters by aufrank

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (2)
As of 2024-04-20 03:58 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found