sorting delimited file in perl

Posted on 2003-02-22
Medium Priority
Last Modified: 2013-12-25
Here is a peice of my code

open (ORGDB,"<$database");
close (ORGDB);

foreach $rec (@ODB){
print "<tr><td>$productID</td><td>$itemname<td></td><td>$description</td></tr>\n";

How do I sort the data by itemname from a-z before it gets printed out to the page?  I dont want to rewrite the file in the new order, i just want the data to show up on the page in order
Question by:derek4716

Expert Comment

ID: 8000177
What you should do is sort @ODB after reading it, mybe something like :

@ODB = sort(@ODB);


@SortedODB = sort(@ODB);

Anyway, remember that sort works according to ASCII code, and this means that 'Z'(uppercase) comes before 'a'(lowercase). If you don't care about the case, you can use lc, uc or preferably ucfirst to change the case of strings..
for example:

@ODB = sort(@ODB);

This is not a perfect solution and there are better ones, after all perl was made for this SORT (he he) of tasks, but I'm too tired to think of it. Hope this helps anyway.

Author Comment

ID: 8000560
thanks for the response ShaharEvron,

I need to sort by the itemname feild though, I forgot to mention that, sorry.
LVL 85

Accepted Solution

ozo earned 800 total points
ID: 8002217
@ODB = sort{ (split/\|/,$a)[1] cmp (split/\|/,$b)[1] } @ODB;
@ODB = map{ $_->[0] }
       sort{ $_->[1] cmp $_->[1] }
       map{ [$_,(split/\|/)[1]] }

Featured Post

Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In this tutorial I will show you how to make a simple HTML bar chart with the usage of WhizBase, If you want more information about WhizBase please read my previous articles at http://www.experts-exchange.com/ARTH_5123186.html (http://www.experts-ex…
This article is meant to give a basic understanding of how to use R Sweave as a way to merge LaTeX and R code seamlessly into one presentable document.
Learn the basics of while and for loops in Python.  while loops are used for testing while, or until, a condition is met: The structure of a while loop is as follows:     while <condition>:         do something         repeate: The break statement m…
In this fifth video of the Xpdf series, we discuss and demonstrate the PDFdetach utility, which is able to list and, more importantly, extract attachments that are embedded in PDF files. It does this via a command line interface, making it suitable …
Suggested Courses

601 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question