Hello wise ones. I'm playing around with Moose, with a view to using a class to represent an XML element and ultimately to generate the XML itself. The below code works but I am not entirely happy with the use of the predicate method to determine if each attribute (the majority of which are optional) needs to be included in the resulting XML. Is there a better way I can approach this? I have considered trigger and after methods to record the attributes that have been set but both feel equally clumsy.
Many thanks.
package Button;
use Moose;
use namespace::autoclean;
use XML::Writer;
has 'name' => ( is => 'rw', isa => 'Str', required => 1);
has 'x' => ( is => 'rw', isa => 'Int', predicate => 'has_x');
has 'y' => ( is => 'rw', isa => 'Int', predicate => 'has_y');
has 'w' => ( is => 'rw', isa => 'Int', predicate => 'has_w');
has 'h' => ( is => 'rw', isa => 'Int', predicate => 'has_h');
sub to_xml {
my ($self) = @_;
my %attr;
$attr{name} = $self->name;
$attr{x} = $self->x if $self->has_x;
$attr{y} = $self->y if $self->has_y;
$attr{w} = $self->w if $self->has_w;
$attr{h} = $self->h if $self->has_h;
my $writer = XML::Writer->new( OUTPUT => 'self' );
$writer->emptyTag('button', %attr);
return $writer->to_string;
}
__PACKAGE__->meta->make_immutable;
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.