Hello sandorado, and welcome to the Monastery!
You’ve already been given excellent advice, and GrandFather’s hash design is probably just what you need. But something about your problem description — “how to save which polygon and rectangle belongs to which class” — is making me think that you might benefit from an object-oriented solution. So, in Perl’s spirit of TMTOWTDI, here is an OO approach:
#! perl use strict; use warnings; use XML::Twig; #--------------------------------------------------------------------- +--------- package Shape; use Moo; use namespace::clean; has type => ( is => 'ro' ); has class => ( is => 'ro' ); has coords => ( is => 'ro' ); sub print { my $self = shift; printf qq[<%s class = "%s" coordinates = "%s">\n], $self->type, $self->class, $self->coords; } #--------------------------------------------------------------------- +--------- package main; my $twig = XML::Twig->new; $twig->parse( do { local $/; <DATA> } ); my @shapes; for my $class ($twig->root->children('class')) { my $class_name = $class->att('id'); push @shapes, Shape->new(type => $_->gi, class => $class_name, coords => $_->att('coordinates')) for $class->chil +dren; } $_->print() for @shapes; __DATA__ <data> <class id="abc"> <polygon coordinates="AA"/> <polygon coordinates="BB"/> <rectangle coordinates="CC"/> </class> <class id="def"> <polygon coordinates="DD"/> <rectangle coordinates="EE"/> <rectangle coordinates="FF"/> </class> </data>
Output:
23:58 >perl 967_SoPW.pl <polygon class = "abc" coordinates = "AA"> <polygon class = "abc" coordinates = "BB"> <rectangle class = "abc" coordinates = "CC"> <polygon class = "def" coordinates = "DD"> <rectangle class = "def" coordinates = "EE"> <rectangle class = "def" coordinates = "FF"> 23:58 >
I have assumed XML as the input and borrowed heavily from poj’s solution using XML::Twig. This OO approach may be overkill for your needs; but, if you’ll need to manipulate your shapes in any non-trivial way, it may provide you with necessary flexibility by de-coupling the shapes from their XML encoding.
Hope that helps,
| Athanasius <°(((>< contra mundum | Iustus alius egestas vitae, eros Piratica, |
In reply to Re: Creation of Hash necessary?
by Athanasius
in thread Creation of Hash necessary?
by sandorado
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |