On 6/4/07, GMan <[EMAIL PROTECTED]> wrote:

sub new {
    my ($class) = @_;
    my ($self) = { };
    bless $self, $class;
    $self->{'_name'} = "";
    @friends = { };

Wait, what was that? Where did this @friends variable come from? It
should probably be a 'my' variable; if you have 'use strict' and 'use
warnings' enabled, Perl will tell you if you forget a 'my'.

But what were you assigning to it? A reference to an empty hash? I
think you meant this:

 my @friends = ( );    # an empty list - no friends :-(

And that's the same as this:

 my @friends;  # think I can really dance :-)

    $self->{'_friends'} = [EMAIL PROTECTED];
    return $self;
}

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;
       }

sub print {
    my ($self) = @_;
    printf("Name %s\n",$self->{'_name'});
    printf("Friends URLs\n");

Using printf is a sure sign of an unreformed C programmer. C uses
printf because C doesn't have string interpolation. Unless you're
using printf for columnar formatting, it has the undocumented side
effect of making other Perl programmers snicker at you behind your
back. But although there's no justification for the second one, the
first printf at least avoids the problem of trying to interpolate a
dereferencing expression, which I'd avoid like this:

   print "Name ", $self->{'_name'}, "\n";

Do these suggestions get you on the road to success? Good luck with it!

--Tom Phoenix
Stonehenge Perl Training

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to