I was poking around in yet another odd corner of Perl, attributes.pm, and I noticed an interesting possibility. According to the pod, the statements,
should have the effect,=pod package Canine; package Dog; my Canine $spot : Watchful ;
If all is well, &attributes::import calls Canine::MODIFY_SCALAR_ATTRIBUTES(Canine => \$spot, 'Watchful') to handle the attribute bookkeeping.use attributes (); attributes::->import(Canine => \$spot, "Watchful"); =cut
"Well," I thinks, "Don't that look just like a constructor?"
If MODIFY_SCALAR_ATTRIBUTES() is written as a constructor, then my Dog $spot; could call it on $spot and give us a dog with that purely declarative syntax. So here goes . . .
I'll simplify the example a little bit, making only one canid class,
The bark is to let us know that the constructor has been called. This is an experiment, after all, and experiments need instruments.use warnings; use strict; package Dog; sub MODIFY_SCALAR_ATTRIBUTES { my $class = shift; my $ref = shift; my %dog; @dog{@_} = (1) x @_; $$ref = \%dog; bless $$ref, $class; print "Woof!\n"; (); }
For a demonstration, we don't need any more methods than that. Time to test drive:
Which faithfully prints:package main; my Dog $spot :Watchful Muddy; my $izzie = ref $spot; print $izzie? "$izzie Spot is @{[keys %$spot]}": "No Spot", $/;
Woof!
Dog Spot is Muddy Watchful
This is nifty all right, but it turns out to have a problem. I'd like to call the constructor with just,
Perl accepts that, but there's no "Woof!" when it runs. No Rover. Instrumenting a private copy of attributes.pm shows that &attributes::import is never called when the attribute list is empty. That's not what I expected, but I can't find any promises in the docs to say it should. In fact, that's very like the behavior of use with no import list.my Dog $rover;
The empty attribute list would be no problem for attributes.pm. Its import() function is structured to work with that.
Having that syntax available would make very happy those people who like strict typing, and I don't think it would rock the structure of Perl much. I haven't yet gone source diving to see what's needed to make that happen. Does anybody have a feel for that?
After Compline,
Zaxo
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: my Dog $spot;
by xdg (Monsignor) on Jun 06, 2006 at 14:21 UTC | |
by Zaxo (Archbishop) on Jun 07, 2006 at 07:19 UTC | |
by TedYoung (Deacon) on Jun 07, 2006 at 16:24 UTC | |
by TimToady (Parson) on Jun 07, 2006 at 18:01 UTC | |
by Zaxo (Archbishop) on Jun 08, 2006 at 01:28 UTC | |
Re: my Dog $spot;
by TedYoung (Deacon) on Jun 06, 2006 at 13:02 UTC | |
by leriksen (Curate) on Jun 06, 2006 at 22:59 UTC | |
Re: my Dog $spot;
by perrin (Chancellor) on Jun 06, 2006 at 16:23 UTC | |
by Zaxo (Archbishop) on Jun 07, 2006 at 05:28 UTC | |
Re: my Dog $spot;
by Zaxo (Archbishop) on Jun 08, 2006 at 05:10 UTC |