One of my most and least favorite features of OO in Perl is that method calls are dynamic. Dynamic method calls means you can write code like this:
The other edge of the sword means that you can call methods that don't exist and Perl can't catch them untill run-time. Which is annoying and can be a pain to track down in your code. One technique that helps ease that pain is to define an AUTOLOAD method in the base class to tell you when you've called a method that doesn't exist (possibly due to a typo) as opposed to other run-time errors (such as trying to call a method on an undefined value).... my $recs = $dbh->selectall_arrayref( $sql ); my @people; foreach my $rec ( @$recs ) { my $i = 0; my $person = Person->new(); foreach my $meth ( qw( name hight weight age gender dob ) ) { $person->$meth( $rec->[$i++] ); } push @people, $person; }
With an AUTOLOAD in the base class, code that calls methods that don't exist, like:package Base; use strict; use warnings; our @ISA = qw(); use vars qw( $AUTOLOAD ); sub new { ... } sub throw { my $self = shift; my($p,$f,$l) = caller(); die "Exception at: ",$p,"->$f($l)\n ",join('',@_); } # report non-existant methods sub AUTOLOAD { my($self) = @_; $self->throw("Error, unsupported method: $AUTOLOAD\n"); } 1;
Will now throw an exception that tells you right where (package, file and line number) the offending code tried to call the non-existant method. This technique has helped reduce the time I spend debugging.$person->shoeSize();
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |