Hi Eelco,
If you're data file isn't excessively large, you might use the following
example. Otherwise, you should probably stuff you data file into a database
,such as CSV or mysql, and use the DBI (available at www.cpan.org) for
processing.
The following code reads in each line of $data_file, removes the trailing
newline, and splits the record into its corresponding fields on the pipe '|'
character. Each record is stored as an anonymous hash (i.e., hash reference)
in the @records array. The sorting is done with a single sort statement that
sorts records by the groep2 field ascending alphabetically. Output is in an
HTML table, but can be changed very easily.
I hope that helps.
Best regards,
David
__END__
#
# Read each line of $data_file, and store in the @records array.
#
my $data_file = 'Macintosh HD:Temp:data.txt';
my @records = ();
open(DATABASE, "< $data_file")
or die "Can't open $data_file for reading: $!";
while(<DATABASE>) {
chomp; # remove trailing \n from $_
my($groep2, $groep_id2) = split '\|'; # same as: split('\|', $_)
# Save record as an anonymous hash (hash reference)
# inside @data
push @records, {
groep2 => $groep2,
groep_id2 => $groep_id2
};
}
close(DATABASE);
#
# Sort @data by groep2 (ascending alphabetically).
# Some notes:
#
# 1. $a and $b are aliases to two elements of @records.
# 2. The 'cmp' operator says we're doing string comparisons
# (we would have used <=> for comparing numbers).
# 3. Placing the $a->{groep2} on the left side of the
# comparison operator 'cmp' means that we want things
# sorted ascending. If you'd like sorting done descending
# alphabetically, then place $b on the left side and
# $a on the right side of the comparison operator.
#
@data = sort { $a->{groep2} cmp $b->{groep2} } @records;
#
# Output each record in an HTML table
#
print <<'END_HTML';
<TABLE BORDER=1>
<TR>
<TH> groep2 </TH>
<TH> groep_id2 </TH>
</TR>
END_HTML
foreach my $record (@records) {
print <<" END_HTML";
<TR>
<TD> $record->{groep2} </TD>
<TD> $record->{groep_id2} </TD>
</TR>
END_HTML
}
print "</TABLE>\n";
At 3/2/2003 9:48 AM, Eelco Alosery wrote:
> Hello,
>
> I'm having truble sorting a database.
> I use this script to open and read a database:
> open (DATABASE, "$data_file") || die "Can't Open $data_file";
> while(<DATABASE>)
> {
> ($groep2, $groep_id2) = split(/\|/,$_);
> foreach ($groep2)
> {
> print <<ENDOFTEXT;
> $groep2<br>
> ENDOFTEXT
> }
> }
> close(DATABASE);
>
> The problem I have is that I want $groep2 to be display't alfabetical.
> I have tested several options using the sort comand but I cant get it
> to work the way I want.
>
> How do I do this sorting.
> Thanks
>