Hey monks.
I'm having a stab at writing my first OO module. All is going well, and I'm enjoying it, but I have stumbled upon a problem. The underlying hash of my object has a sub-hash, so to speak, called 'options'. (When I
bless it, it's like this:)
bless {foo => 'bar',
options => {anoption => 1,
anotheroption => 'foo',
option3 => 'barbar'},
bar => 'maz'}, $class;
The
options hash has a lot of keys, so I thought I could write a subroutine to return an element. Here's my try:
sub option { shift->{options}->{shift()} }
All goes well, until I have to modify a value in the options hash. I'm sure there's a very simple way to do this. I tried this:
sub option {
my $self = shift;
if (scalar @_ == 1) {
return $self->{options}->{shift()};
} else {
my ($key, $value) = @_;
$self->{options}->{$key} = $value;
}
}
This works, but looks cumbersome. There has to be an easier way to do it. I think I need to be clearer on hash assignment in general, as well. I always thought that you say this:
%hash = @array and the pairs described by
@array would be added to
%hash, instead of wiping the hash and then adding them. This doesn't happen, and the only way I can think of accomplishing the same thing is to divide the array into two array based on modulo 2, to get the effective keys and values, then using a hash slice to assign them. Again, very cumbersome.
I'm sure many OO modules have done this, but I searched for examples in vain. An example, preferably supporting changing of more than one element, would be great.
--
my one true love
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.