From: "Tom Phoenix" <[EMAIL PROTECTED]>
> On 6/4/07, GMan <[EMAIL PROTECTED]> wrote:
> Things go smoothly for a while, and things seem quiet. Too quiet. Then...
>
> > sub addfriend {
> > my ($self,$f) = @_;
> > #dereference the array from the hash
> > $fr = $self->{'_friends'};
> > @friends = @$fr;
> > push @friends,$f;
> > $self->{'friends'} = [EMAIL PROTECTED];
> > }
>
> It looks as if (for lack of 'my') this subroutine is also using the
> same @friends that we saw earlier, the package variable also known as
> @Person::friends. If that doesn't sell you on 'use strict', nothing
> will.
>
> But 'strict' won't tell you when you write 'friends' instead of
> '_friends' for a hash key, and 'warnings' won't say that your code
> could be written more simply. I think this is it:
>
> sub addfriend {
> my ($self, $newfriend) = @_;
> # dereference the array from the hash
> my $friendsref = $self->{'_friends'};
> push @$friendsref, $newfriend;
> }
Or even just
sub addfriend {
my ($self, $newfriend) = @_;
# dereference the array from the hash
push @{$self->{'_friends'}}, $newfriend;
}
Just like you use () to make sure mathematical operators are applied
the way you want you use {} to make sure dereferencing is done right.
You might also change the subroutine a little to allow for
$obj->addfriend( 'Tom', 'Jenda')
like this:
sub addfriend {
my ($self, @newfriends) = @_;
# dereference the array from the hash
push @{$self->{'_friends'}}, @newfriends;
}
Jenda
===== [EMAIL PROTECTED] === http://Jenda.Krynicky.cz =====
When it comes to wine, women and song, wizards are allowed
to get drunk and croon as much as they like.
-- Terry Pratchett in Sourcery
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/