in reply to Predefining complex data structures?

First off you cant "predefine" your data structure in Perl. There is no means by which you can explicitly specify your data structure. Instead Perl provides for easy ways to implicitly define your data structure. As well as interact with it and redefine it on the fly.

So how to do some of the things you want to do...

my %struct; foreach my $elem (@elements) { # loop over all the elements # check to make sure our hash key has an array we can push onto. $struct{$elem->name}=[] unless $struct{$elem->name}; # now create a new sub hash to push onto the array later my %hash=(text=>$elem->text, attributes=>[]); #initialize it # loop over each attribute in the element foreach my $attrib ($elem->attribs) { # push the elements onto the attributes array push @{$hash{attributes}},$attrib->name,$attrib->value; } # push a reference to the newly created hash on the array stored for + this element type. push @{$struct{$elem->name}},\%hash; }
Now of course you will have to figure out how to convert the pseudo methods ive used here into the real thing. Also, iirc XML does not allow for two attributes of the same name in one tag, so instead of using an array to store them just use a hash (unless of order is important).

HTH

UPDATE The line where I put an array in explicitly is not needed in this scenario, but if we code like

push @{$hash{$key}},'var' unless @{$hash{$key}}>5;
we would, because autovivification doesnt happen in that context. Sorry. And just now in the CB chip pointed out that changing the condition to
push @{$hash{$key}},'var' unless @{$hash{$key}||[]}>5;
would also do the trick, and is probably more elegant, if a touch obfu'd. Thanks chip.

Yves / DeMerphq
---
Writing a good benchmark isnt as easy as it might look.

Replies are listed 'Best First'.
Re: Re: Predefining complex data structures?
by chip (Curate) on Jul 12, 2002 at 15:43 UTC
    Thanks for the nod, demerphq, but I think I can do it my hack one better:

    for ($hash{$key}) { push @$_, 'var' unless @$_ > 5 }

        -- Chip Salzenberg, Free-Floating Agent of Chaos

      I understand the rest of the snippet but I'm missing the signficance of the 5. Why 5?
        Beats me why five. It was in the code I was revising.

            -- Chip Salzenberg, Free-Floating Agent of Chaos

        It was just "some condition" that happened to pop into my head. No signifigance whatsoever.

        :-)

        Yves / DeMerphq
        ---
        Writing a good benchmark isnt as easy as it might look.

Re: Re: Predefining complex data structures?
by Ionizor (Pilgrim) on Jul 12, 2002 at 15:24 UTC
    Heh... I put square brackets instead of braces in my example. I did mean for the attributes to be in a hash rather than an array. Oops!