[ale] OOP in perl

Fletch fletch at phydeaux.org
Fri Apr 25 09:42:41 EDT 2003


>>>>> "Christopher" == Christopher Fowler <cfowler at outpostsentinel.com> writes:

[...]

    > my %addr = { 'Name' => "",

You mean either `my %addr = ( ... )' or `my $addr = { }'.  This should
have griped about assigning an odd number of items to a hash (since a
hashref is only a single scalar value).


    >    bless \%addr, 'Address';
    >    return %addr;

Perl objects are blessed references.  You return the hash itself
(which gets flattened out into a list of key value pairs), and the
blessed hash disappears when the scope ends.  You really want
something more along these lines:


sub new {
  my $class = shift;
  my $self = { ... };

  return bless $self, $class
}


If you want to be able to call new() on existing instances you may
want to add in `$class = ref($class) || $class;' in there somewhere,
but that's not required (even though lots of people cargo cult it into
everything (even I'm guilty of that :)).



    > # If I do not place a return 1 at the end, I get the 
    > # following error
    > #Address.pm did not return a true value at ./test line 4.
    > #BEGIN failed--compilation aborted at ./test line 3.

Erm, yes.  Perl requires modules to return a true value to indicate
they've successfully loaded.  See perldoc perlmod.


    > my $addr = Address::new(); $addr->test();

You mean `Address->new()'.  `Address::new()' is just invoking a sub
using its fully qualified name.  Not that it matters in this case
because your new() ignores what it was called on, but for future
reference.


    > --- Execution --- [cfowler at cfowler OOP]$ perl test 
    > Can't call method "test" without a package or object reference at test line 7.
    >  [cfowler at cfowler OOP]$

This is because $addr doesn't contain a blessed reference (see first
comment).


Back to the documentation mines with you! :)


perlreftut          Perl references short introduction
perlboot            Perl OO tutorial for beginners
perltoot            Perl OO tutorial, part 1
perltooc            Perl OO tutorial, part 2
perlbot             Perl OO tricks and examples


See also _Object Oriented Perl_ by Damian Conway.  If you have one
other perl book besides the Camel and the cookbook, it should be OOP.


-- 
Fletch                | "If you find my answers frightening,       __`'/|
fletch at phydeaux.org   |  Vincent, you should cease askin'          \ o.O'
770 294-0820 (m)      |  scary questions." -- Jules                =(___)=
                      |                                               U
_______________________________________________
Ale mailing list
Ale at ale.org
http://www.ale.org/mailman/listinfo/ale





More information about the Ale mailing list