PERL CGI Tutorial for Writing Interactive Form Scripts
Sort a File
It doesn't require much code to perform a simple bubble sort using PERL. We just open a file dump its contents into and array, sort the array to a new name and display or process the new array.
We can modify the CGI script display_file.pl to perform the task.
The code for performing the simple sort is shown below.
There are some problems with this kind of sorting. Strings are sorted by their ascii values. A (65) and a (97) will be sorted by their ascii values respectively. Numbers would also be sorted incorrectly. We'll introduce another sort routine when we get to manipulating numbers in PERL.
@sortedarray=sort(@array);
The code for display_file.pl is show below with changes in red.
#!/usr/bin/perl
print "Content-type:text/html\n\n";
print "<html>\n";
print "<head><title></title></head>\n";
print "<body>\n";
open(INFO, "names.txt");
@array=<INFO>;
close (INFO);
@sortedarray=sort(@array);
foreach $line (@sortedarray){
print "$line<br>\n";
}
print "</body>\n";
print "</html>\n";
Remember to Refresh the page after modifications.
Other Variations of the Script
Display the File in a Table
Display the file in a Scrolling Textarea
|