giulienk has asked for the wisdom of the Perl Monks concerning the following question:

I few days ago i posted here looking for support to my new project WWW::SMS: thank you for suggestions.
Anyway the new() method is now more beautiful and standardized as it allows for free optional parameters in hash fashion.
Now it's coded like this:
sub new { my ($self, $key, $value); my $class = shift; my ($intpref, $prefix, $telnum, $smstext, %hash) = @_; $self = bless { 'intpref' => $intpref, 'prefix' => $prefix, 'telnum' => $telnum, 'smstext' => $smstext, 'cookie_jar' => exists $hash{cookie_jar} ? delete $hash{cookie_jar} : "lwpcookies.txt", }, $class; for (($key, $value) = each %hash) { $self->{$key} = $value; } $self; }
Is there any better way to code the last part of the method where i just put every remaining hash value into the object?
Is there a way to do it without cycling over the hash?
Bye and thanks.
Giulio

Replies are listed 'Best First'.
Re: Optional parameters in new() method
by Kanji (Parson) on Oct 26, 2001 at 00:09 UTC

    Just put %hash inside bless {} directly ...

    $self = bless { 'intpref' => $intpref, 'prefix' => $prefix, 'telnum' => $telnum, 'smstext' => $smstext, 'cookie_jar' => "lwpcookies.txt", %hash, }, $class;

    ... which has the added benefit of making defaults real easy, because the user can just insert a key/value pair for whatever they want to override (ie, 'cookie_jar' in the above: if it exists in %hash, the new value will replace the default), saving you of going through the motions of 'key' => exists $hash{'key'} ? delete $hash{'key'} : 'my default',.

    And since you don't use %hash anywhere else, you could feasibly rid yourself of temporary assignments by reducing the above to...

    sub new { my $class = shift; my $self = bless { 'intpref' => shift, 'prefix' => shift, 'telnum' => shift, 'smstext' => shift, 'cookie_jar' => "lwpcookies.txt", @_, }, $class; # ... other things with $self ... $self; }

        --k.


Re: Optional parameters in new() method
by dragonchild (Archbishop) on Oct 25, 2001 at 23:21 UTC
    You could try hash slices. :-)
    @{$self}{keys %hash} = @hash{keys %hash};
    That will do pretty much exactly what you're doing.

    However, as a stylistic note, if you're doing OO for the benefits of OO (encapsulation and the like), then this is generally bad. You're allowing someone to mess with your internals. Not the best plan.

    But, if you're using OO as a glorified data structure (which is perfectly fine!), then this is just fine.

    ------
    We are the carpenters and bricklayers of the Information Age.

    Don't go borrowing trouble. For programmers, this means Worry only about what you need to implement.

Re: Optional parameters in new() method
by tomhukins (Curate) on Oct 25, 2001 at 23:20 UTC
    I missed the original thread, but it sounds like you're duplicating the functionality of Net::SMS::Web.