(innermost) subroutine is referencing a lexical variable defined in
the outermost subroutine. For example:
- sub outermost { my $a; sub middle { sub { $a } } }
+ sub outermost { my $x; sub middle { sub { $x } } }
If the anonymous subroutine is called or referenced (directly or
indirectly) from the outermost subroutine, it will share the variable
That's not fun yet. Same number of characters, all constant, no
variables. But yet, the parts are separable now. Watch:
- $a = "Cow";
- $a->speak; # invokes Cow->speak
+ $x = "Cow";
+ $x->speak; # invokes Cow->speak
Ahh! Now that the package name has been parted from the subroutine
name, we can use a variable package name. And this time, we've got
or the equivalent:
- $a = "Class";
- $a->method(@args);
+ $x = "Class";
+ $x->method(@args);
which constructs an argument list of:
package main;
- $a = Foo->new( 'High' => 42, 'Low' => 11 );
- print "High=$a->{'High'}\n";
- print "Low=$a->{'Low'}\n";
-
- $b = Bar->new( 'Left' => 78, 'Right' => 40 );
- print "Left=$b->[0]\n";
- print "Right=$b->[1]\n";
-
+ $x = Foo->new( 'High' => 42, 'Low' => 11 );
+ print "High=$x->{'High'}\n";
+ print "Low=$x->{'Low'}\n";
+
+ $y = Bar->new( 'Left' => 78, 'Right' => 40 );
+ print "Left=$y->[0]\n";
+ print "Right=$y->[1]\n";
+
=head1 SCALAR INSTANCE VARIABLES
An anonymous scalar can be used when only one instance variable is needed.
package main;
- $a = Foo->new( 42 );
- print "a=$$a\n";
+ $x = Foo->new( 42 );
+ print "a=$$x\n";
=head1 INSTANCE VARIABLE INHERITANCE
package main;
- $a = Foo->new;
- print "buz = ", $a->{'buz'}, "\n";
- print "biz = ", $a->{'biz'}, "\n";
+ $x = Foo->new;
+ print "buz = ", $x->{'buz'}, "\n";
+ print "biz = ", $x->{'biz'}, "\n";
package main;
- $a = Foo->new;
- print "buz = ", $a->{'Bar'}->{'buz'}, "\n";
- print "biz = ", $a->{'biz'}, "\n";
+ $x = Foo->new;
+ print "buz = ", $x->{'Bar'}->{'buz'}, "\n";
+ print "biz = ", $x->{'biz'}, "\n";
package main;
- $a = FOO->new;
- $a->bar;
+ $x = FOO->new;
+ $x->bar;
Now we try to override the BAZ() method. We would like FOO::bar() to call
GOOP::BAZ(), but this cannot happen because FOO::bar() explicitly calls
package main;
- $a = GOOP->new;
- $a->bar;
+ $x = GOOP->new;
+ $x->bar;
To create reusable code we must modify class FOO, flattening class
FOO::private. The next example shows a reusable class FOO which allows the
package main;
- $a = GOOP->new;
- $a->bar;
+ $x = GOOP->new;
+ $x->bar;
=head1 CLASS CONTEXT AND THE OBJECT
package main;
- $a = Bar->new;
- $b = Foo->new;
- $a->enter;
- $b->enter;
+ $x = Bar->new;
+ $y = Foo->new;
+ $x->enter;
+ $y->enter;
=head1 INHERITING A CONSTRUCTOR
package main;
- $a = BAR->new;
- $a->baz;
+ $x = BAR->new;
+ $x->baz;
=head1 DELEGATION