sub new { my $this = {}; # Create an anonymous hash, and #self points to it. bless $this; # Connect the hash to the package Cocoa. return $this; # Return the reference to the hash. }
1; {}创建一个对不含键/值对的哈希表(即关联数组)的引用,返回值被赋给局域变量$this。函数bless()取出该引用,告诉对象它引用的是Cocoa,最后返回该引用。函数的返回值现在指向这个匿名哈希表。 从new()函数返回后,$this引用被销毁,但调用函数保存了对该哈希表的引用,因此该哈希表的引用数不会为零,从而使Perl在内存中保存该哈希表。创建对象可如下调用: $cup = new Cocoa;