in reply to Population of an array

Alright...so you have a bit of a mess and its painfully obvious that you havn't even tried running the code you presented to us. Why? Well we can leave that for another time. Basicaly you are trying to parse XML, there are many better ways to do this than by hand. There are so many special cases with this kind of data that you realy realy realy ought to go search CPAN.org and find a module that fits your needs. In the interest of helping you and honestly just because it sounded kinda fun, i wrote a quick script that kind of does what you want.

The script starts with 2 very important lines that you should *ALWAYS* use. Until you understand why you can remove them, don't. Never remove them simply because you get an error that you don't understand, that is a good way to get hidden bugs and avoid learning. I then declare two data structures. my $data = {}; creates a hashref which will let me store data associated with a key. Then my @keys; is an array that will hold the current keys gotten from tags it is reading. while (<DATA>) { is going to loop over all the data in the __DATA__ section at the end of the file. This is usefull for quick test scripts where you want the data close at hand. From there the script gets more complicated. First we check to see if this is the begging of a tag...the regex is not right but it works for your example code. This is part of the reason you don't do this processing by hand in production code. If its a start tag, then push the tag name onto our keys array. If its not a start then maybe it an end, if it is an end, then pop it off the keys array. I do a quick check to make sure that the tag you are closing is actualy open. Last, if its not an open or a close then its data so i join my current keys together with a '-' and put the data into that key's slot in the array. Hopefully that helped you more than it confused you! Lastly i use Dumper($data) to print the data out in a pretty manner.

#here is the output of my script $VAR1 = { 'tag1-slow' => 'Increase your speed.', 'tag1-fast' => 'Slow down boy!!!', 'tag2-fast' => 'Slow down boy!! BIG HEAD!', 'tag2-slow' => 'Increase your speed.' };
use strict; use warnings; use Data::Dumper; my $data = {}; my @keys; while (<DATA>) { chomp; if ($_ =~ /<([^>\/]*)>/) { push @keys, $1; } elsif ($_ =~ /<\/([^>]*)>/) { if ($keys[-1] eq $1) { pop @keys; } else { die "Invalid Nesting"; } } else { $data->{ join("-", @keys) } .= $_; } } print Dumper($data); __DATA__ <tag1> <fast> Slow down boy!!! </fast> <slow> Increase your speed. </slow> </tag1> <tag2> <fast> Slow down boy!! BIG HEAD! </fast> <slow> Increase your speed. </slow> </tag2>

___________
Eric Hodges

Replies are listed 'Best First'.
A reply falls below the community's threshold of quality. You may see it by logging in.