VinsWorldcom has asked for the wisdom of the Perl Monks concerning the following question:
I know object-oriented programming in that I can use others' modules and I've written some of my own. I've read perlobj and perlootut. However, most of my objects have been simply nested Perl data structures (e.g., HoH, HoAoH, etc.). I have no problem creating or accessing those types of objects.
I'm keen to learn more about how to do this more "?correctly?". So I started looking into Class::Struct since it's simple, for building classes and in Perl core.
Take the following code borrowed heavily from the examples in the Class::Struct perldoc:
use strict; use warnings; package Cat; use Class::Struct; struct (name => '$'); 1; package Litter; use Class::Struct; struct (cats => '@'); 1; package main; my $cat1 = Cat->new(name=>'Garfield'); my $cat2 = Cat->new(name=>'Felix'); my $litter = Litter->new(cats => [$cat1, $cat2]); for (@{$litter->cats}) { print $_->name . "\n" }
This works swimmingly until $litter is created like so:
my $litter = Litter->new(cats => [$cat1, 1]);
Which of course produces an error ...
Can't call method "name" without a package or object reference at ...
... because "1" doesn't have a method - in fact, it's not even an "object". What I really 'think' I need to do is define the Litter object like so:
package Litter; use Class::Struct; struct (cats => '@Cat'); 1;
Meaning the 'cats' method should contain an array of 'Cat' objects, not just an array of anything. The documentation for Class::Struct leads me to believe I can't do it.
Questions:
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Perl OO with Class::Struct
by tobyink (Canon) on Dec 13, 2013 at 16:21 UTC | |
|
Re: Perl OO with Class::Struct
by davido (Cardinal) on Dec 13, 2013 at 16:09 UTC | |
by tobyink (Canon) on Dec 13, 2013 at 16:24 UTC | |
by davido (Cardinal) on Dec 13, 2013 at 16:33 UTC | |
|
Re: Perl OO with Class::Struct
by educated_foo (Vicar) on Dec 13, 2013 at 15:30 UTC | |
|
Re: Perl OO with Class::Struct
by dbuckhal (Chaplain) on Dec 17, 2013 at 07:43 UTC |