Re: Magic for object constructor wanted
- From: Peter Scott <Peter@xxxxxxxx>
- Date: Thu, 31 Jan 2008 15:58:27 GMT
On Wed, 30 Jan 2008 22:05:45 -0800, Koszalek Opalek wrote:
My code creates new objects and then populates them with
data, like this:
my $joe = Dude->new();
my $tom = Dude->new();
my $ann = Dude->new();
my $jane = Dude->new();
$joe->fill(
name => "joe",
friends => [ $ann, $tom ]
);
$jane->fill(
name => "jane",
friends => [ $ann ]
);
You will notice that the name field is always the same as
the variable that stores the object. What kind of magic
would I have to use in the constructor (or in the fill()
method) so that 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.
Is this possible?
Possible, yes. Ugly, too. What you want is a sure-fire sign of a bad
design. I'm only going to show how to do it as an academic exercise to
demonstrate that Perl makes even bad ideas possible. I'm not going to
answer any questions about it. I think it would be a hideous mistake to
put it in production code.
$ cat /tmp/foo
#!/usr/local/bin/perl
use strict;
use warnings;
use PadWalker qw(peek_my);
use List::Util qw(first);
my $my_name = 42;
get_name(\$my_name);
sub get_name {
my $ref = shift;
my $h = peek_my(1);
my $name = first { ref $ref && $h->{$_} eq $ref } keys %$h;
print "Object variable name = ", ($name || "<???>"), "\n";
}
$ /tmp/foo
Object variable name = $my_name
--
Peter Scott
http://www.perlmedic.com/
http://www.perldebugged.com/
.
- References:
- Magic for object constructor wanted
- From: Koszalek Opalek
- Magic for object constructor wanted
- Prev by Date: Re: Can't get PAR packager to run pp
- Next by Date: Re: "negative" regexp
- Previous by thread: Re: Magic for object constructor wanted
- Next by thread: FAQ 1.4 What are Perl 4, Perl 5, or Perl 6?
- Index(es):
Relevant Pages
|