I wonder if there is an "official" way to retrieve the order in which attributes have been declared in a Moose-based class
No, there is no official way, Moose stores the attributes in a hash, so they are essentially unordered.
Depending on your needs, there are a number of ways to go about this. The simplest is to make a custom meta-attribute that can take an "order" field. There is a recipe for custom meta-attributes and meta-attribute traits in the Moose::Cookbook and the Moose::Manual also touches on this topic a little too. If you did this then you could write your code like so:
Then you could simply get all the attribute using Hubba->meta->get_all_attributes and sort them by their order field. The obvious drawback here is that you have to specify the ordering yourself. Of course with a little trickery and some class level data in your custom meta-attribute you could probably avoid this.package Hubba; use Moose; has abba => (metaclass => 'MyOrderedCustomAttribute', is => 'rw', orde +r => 1); has zappa => (metaclass => 'MyOrderedCustomAttribute', is => 'rw', ord +er => 2);
Another (slightly more complex) way would be to have a custom meta-class that simply wrapped the add_attribute method and kept an ordered list of attributes to be retrieved later. The Moose::Cookbook and Moose::Manual also touch on custom meta-classes as well.
One thing for sure though, you should not reach into private attributes (like $h->meta->{_meta_instance}) to get this kind of data, because they are private and therefore should not be relied upon for code outside of the core Moose.
You might also want to try asking this on the Moose mailing list (moose@perl.org) or on the Moose IRC channel (#moose@irc.perl.org) as you are certainly not the first person who has wanted to do this and other people may have already working solutions that you can use.
In reply to Re: declaration order of attributes in Moose
by stvn
in thread declaration order of attributes in Moose
by morgon
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |