perlquestion
VinsWorldcom
<p>I know object-oriented programming in that I can use others' modules and I've written some of my own. I've read [doc://perlobj] and [doc://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.</p>
<p>I'm keen to learn more about how to do this more "?correctly?". So I started looking into [cpan://Class::Struct] since it's simple, for building classes <b>and</b> in Perl core.</p>
<p>Take the following code borrowed heavily from the examples in the [cpan://Class::Struct] perldoc:</p>
<c>
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"
}
</c>
<p>This works swimmingly until $litter is created like so:</p>
<c>
my $litter = Litter->new(cats => [$cat1, 1]);
</c>
<p>Which of course produces an error ...</p>
<c>
Can't call method "name" without a package or object reference at ...
</c>
<p>... 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:</p>
<c>
package Litter;
use Class::Struct;
struct (cats => '@Cat');
1;
</c>
<p>Meaning the 'cats' method should contain an array of 'Cat' objects, not just an array of anything. The documentation for [cpan://Class::Struct] leads me to believe I can't do it.</p>
<p><b>Questions:</b></p>
<ol>
<li>Is the 'workaround' to override the accessor for 'cats' as shown in Example 2 of the [cpan://Class::Struct] perldoc to check that the value passed is an object of type 'Cat'?</li><br />
<li>Sticking with [cpan://Class::Struct], is there a 'better' way to define the data structure / classes / objects I'm looking for (Litter 'cats' = array of 'Cat') such that I avoid the '@Cat' definition which isn't legal?</li><br />
<li>Have I already 'outgrown' the usefulness of [cpan://Class::Struct] and simply that it's in Perl core is not the best reason to use it?</li><br />
</ol>