Hi Monks.

I am currently learning how to design object oriented programs in Perl and, being very familiar with Java, I began to wonder how the former differs from the latter in this particular aspect. For example:

public class Example { private String name; private int score; public Example(String myName, int myScore) { name = myName; score = myScore; } public String getName() { return name; } }


In the above Java class, both 'name' and 'score' are instance variables with a scope (visibility) that extends to both the constructor and the getName method even though the getName method was not constructed with a parameter (the parentheses are empty). Is Perl constructed in a similar manner? In other words, can 'instance variables' be defined outside a constructor? If so, are they visible within every subroutine (method)?

#!/usr/bin/perl use strict; use warnings; package Example; # Can variables be defined here? With package level # visibility? sub new { my $class = shift; my $self = { _name => shift, _score => shift, }; bless $self, $class; return $self; } sub getName { my ($self) = @_; return $self->{_name} || 'No name has been defined!'; } sub getScore { my ($self) = @_; return $self->{_score} || 'No score has been entered!'; } 1;


Is passing variables between methods a common practice in Perl? Can you define a class method in Perl?

Thanks for the help monks.

An inquisitive monkette

In reply to 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.