CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Intermediate:
Dynamic array names?

 



monocle
User

Apr 10, 2001, 4:49 PM

Post #1 of 3 (150 views)
Dynamic array names? Can't Post

OK... I am parsing some xml data and the exact number of fields is unknown. Each field should have it own array of data. Long story short, I get the different fields and the corresponding data like so:
if ($line =~ /<(.*)>(.*)<\//) {
$id = $1;
$$id[$i] = $2; # $id can equal things like REMOTE_HOST_IP or LOGGED_TIME
}

$i gets incremented in a loop as we move from one set of data to the next. We keep stuffing the data into each of the arrays.

Later in the script I sort all of the arrays like so:
@indices = (0 .. $#REMOTE_HOST_IP);
@sorted_indices = sort { $REMOTE_HOST_IP[$a] <=> $REMOTE_HOST_IP[$b] } @indices;
@REMOTE_HOST_IP = @REMOTE_HOST_IP[@sorted_indices];
# .... 25+ arrays get sorted the same but each one must be specified by name ...
@LOGGED_TIME = @LOGGED_TIME[@sorted_indices];

but I would like to sort all arrays without knowing the names of them like so:
@indices = (0 .. $#REMOTE_HOST_IP);
@sorted_indices = sort { $REMOTE_HOST_IP[$a] <=> $REMOTE_HOST_IP[$b] } @indices;
foreach $field (@FIELDS) {
@$field = @$field[@sorted_indices];
}

So... if that makes any sense... can you help me? I am sure I am just over looking something. I guess it does not like the use of "@$field" like it did with "$$id[$i]"




henning
Deleted

Apr 24, 2001, 4:06 AM

Post #2 of 3 (126 views)
Re: Dynamic array names? [In reply to] Can't Post

Hello,
Why don't you just use a hash to put all your arrays into instead of throwing them into global scope ? then you can go like this :

if ($line =~ /<(.*)>(.*)<\//) {
$id = $1;
$stuff{$id}[$i] = $2;
}
...
and process all of them :
foreach $arrayName (keys %stuff) {
...
@sorted_indices = sort { $stuff{$arrayName}[$a] <=> $stuff{$arrayName}[$b] } @indices;
...
}
hope this helps :)




Henning


henning
Deleted

Apr 24, 2001, 4:09 AM

Post #3 of 3 (126 views)
Re: Dynamic array names? [In reply to] Can't Post

btw,
You might also want to take a look at the XML::Simple module, which does something very similar to what you do.


Henning

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives