on Wed, 31 Jul 2002 12:56:17 GMT, [EMAIL PROTECTED] (Connie Chan)
wrote:
> What I have now is something like this :
> @ID = qw (Foo Bar Blaz Bob);
> @Country = qw (UK US HK HK);
> @Gender = qw (F M M F);
Using parallel arrays to store related data is not a good idea imho.
I would use an (anonymous) array of hashes here:
my $persons = [ { ID => 'Foo', COUNTRY => 'UK', GENDER => 'F' },
{ ID => 'Bar', COUNTRY => 'US', GENDER => 'M' },
{ ID => 'Bla', COUNTRY => 'HK', GENDER => 'M' },
{ ID => 'Bob', COUNTRY => 'HK', GENDER => 'F' }
];
(I don't believe Bob is female though :-)
> %table{ID} = (ID => \@ID, Country => \@Country, Gender =>
> \@Gender); So I got $table{ID}[1] as 'Bar", and I think this is
> HOA.
Did you mean %table = (...) here instead of %table{ID} = (...), which
is a syntax error.
> Note : The above array is always same in dimension, and
> the reading way is Foo's location is in UK and gender is F.
But this is not an array, it is a hash.
> This is fixed, so I can't modify anything on it.
That's a pity, because it really is error-prone.
> But what I going to do is like this :
> my %newTable = SortTable ( TABLE => \%table, Seq => "Gender=A,
> Country=D, ID=A");
> my %newTable = SortTable ( TABLE => \%table,
> Seq => "ID=A, Gender=A, Country=A"); # where =A =D is in terms of
> acending and decending order.
If I understand you correctly, you want to create a new hash, where
the elements in the individual arrays are sorted by your criteria.
> That would really complex if have to write one, so I am looking if
> there is an existed module for this.
Using your datastructure, this would indeed be rather complicated.
If you could use the datastructure I proposed at the beginning of
this post, you could write
sub sortit {
my $array = shift;
my $code = 'sub sortfun { ';
my $first = 1;
while (@_) {
my $s = shift;
my $d = shift;
$code .= ' || ' unless $first;
$first = 0;
$code .= $d eq 'A' ?
"\$a->{$s} cmp \$b->{$s}" :
"\$b->{$s} cmp \$a->{$s}" ;
}
$code .= '}';
undef &sortfun;
eval $code;
my @result = sort sortfun @$array;
return \@result;
}
which builds a sortfunction on the fly per your criteria.
It could then be called as follows:
my $sorted_persons = sortit($persons,
COUNTRY => 'A',
GENDER => 'D',
ID => 'A');
--
felix
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]