2

In Perl, is it possible to list all objects of a specific class?

For example, I have two objects of class Character:

my $char1 = Character->new('John');
my $char2 = Character->new('Adam');

Now, I want to iterate over all Character objects ($char1 and $char2), like :

foreach ( "objects Character" ) {
    print "$_->getName()\n";
}
ikegami
  • 367,544
  • 15
  • 269
  • 518
  • See the question [Perl : Get the objects of a particular class](http://stackoverflow.com/questions/20783341/perl-get-the-objects-of-a-particular-class) - I give a couple of solutions in [my answer](http://stackoverflow.com/a/20788014/1990570). – tobyink Jan 13 '14 at 16:45

1 Answers1

3

No, Perl doesn't maintain a list of objects by class. You'll need to keep track of this yourself.

If you have a fixed number of objects:

my $char1 = Character->new('John');
my $char2 = Character->new('Adam');

for ($char1, $char2) {
    print $_->getName(), "\n";
}

If you have a variable number of objects:

my @chars;
push @chars, Character->new('John');
push @chars, Character->new('Adam');

for (@chars) {
    print $_->getName(), "\n";
}
ikegami
  • 367,544
  • 15
  • 269
  • 518