in reply to Re^2: Object oriented Perl and Java: A brief examination of design.
in thread Object oriented Perl and Java: A brief examination of design.
Could you provide a simple example of how one would use a class variable in Perl?
Sure!
#! perl use strict; use warnings; package Widget { my $count = 0; sub new { my ($class, @args) = @_; my %self = @args; ++$count; return bless \%self, $class; } sub DESTROY { --$count; } sub get_count { return $count; } } package main; my $w1 = Widget->new(name => 'foo', value => 42); my $w2 = Widget->new(name => 'bar', value => 7); my $w3 = Widget->new(name => 'baz', value => 12); printf "Now there are %d Widgets\n", Widget::get_count; undef $w1; printf "Now there are %d Widgets\n", Widget::get_count;
Output:
15:52 >perl 856_SoPW.pl Now there are 3 Widgets Now there are 2 Widgets 15:52 >
Is there any other way, using the code I wrote, to access the value of an instance variable with a method that did not receive the variable as a parameter?
Not that I can think of. Anyway, that’s not how it’s supposed to work in Perl.
a class variable could be defined outside the constructor but still as a lexically scoped, 'my' variable? What about using 'our'?
Using our creates a package variable, which can then be exported to other packages, or accessed directly by other packages using the $Widget::count syntax. Using my creates a lexical variable, which is scoped to the package. The rule is: use a lexical (my) variable unless you have a good reason to make it a package/global (our) variable. Update (Jan 30, 2014): See Ovid’s classic post 'our' is not 'my'.
Hope that helps,
| Athanasius <°(((>< contra mundum | Iustus alius egestas vitae, eros Piratica, |
|
|---|