Chapter 13 Introduction to Objects
use Cow; use Horse; use Sheep; my @pasture = qw(Cow Cow Horse Sheep Sheep); foreach my $beast (@pasture) { no strict 'refs'; &{$beast."::speak"}; # Symbolic coderef, must turn off strict } foreach my $beast (@pasture) { $beast−>speak; # use arrow invocation, no need to turn off strict }
Class−>method(@args) 等價於 Class::method('Class', @args)
第一個參數會加上 "Class Name"
sub sound { 'baaaah' } sub speak { my $class = shift; print "a $class goes ", $class−>sound, "!\n"; }
@ISA is an array, not a simple single value
use Animal; our @ISA = qw(Animal); # use @ISA to declare this class inherit from "Animal" sub sound { "moooo" }
利用 parent 關鍵字來簡化宣告
use v5.10.1; package Cow; use parent qw(Animal);
要呼叫 parent declaration.
package Mouse; use parent qw(Animal); sub sound { 'squeak' } sub speak { my $class = shift; $class−>Animal::speak(@_); # tell it where to start, but need to provide first argument $class−>SUPER::speak(@_); # use SUPER keyword is ok too. print "[but you can barely hear it!]\n"; }
bless
http://stackoverflow.com/questions/392135/what-exactly-does-perls-bless-dobless associates a reference with a package.
If the second argument is omitted, the current package/class is used.
package MyClass; my $object = { }; bless $object, "MyClass";
sub new { my $class = shift; my $self = { }; bless $self, $class; }
Chapter 14 Introduction to Testing
Skip first
沒有留言:
張貼留言