Re: Magic for object constructor wanted



On Jan 31, 7:05 am, Koszalek Opalek <koszalekopa...@xxxxxxxxxx> wrote:

(...)

the name of the object does not have
to be specified explicitly? In other words, I would like to
be able to say:

$joe->fill(
friends => [ $ann, tom ]
);

$jane->fill(
friends => [ $ann ]
);

and still have the name field set. This saves typing and
makes sure the variable name and the name field match.


The following just occurred to me. It would be cool...
if it worked :-) I have created a @Dudes array and then
iterate over the array creating objects dynamically
with eval() and passing whatever I need to the constructor.

The code errors out with
Can't call method "friends" on an undefined value at q.pl line 35.

Is there a way to declare variables with eval() in the
calling scope?

#!/usr/bin/perl
use strict;
no strict "vars";
use warnings;


{
package Dude;

sub new
{
my $class = shift;
my $self = {@_};
print "new() executed\n";
bless $self, $class;
};

sub friends
{
print "hello from $_[0]->{name}\n";
}
}


my @Dudes = ("joe", "tim");

for (@Dudes) {
my $code = qq{my \$$_ = Dude->new( "name" => "$_"); \$joe-
friends();};
print "$code\n";
eval $code;
};

$joe->friends();


__END__

Koszalek
.