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,


In reply to Re^3: Object oriented Perl and Java: A brief examination of design. by Athanasius
in thread Object oriented Perl and Java: A brief examination of design. by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.