dumpexec has asked for the wisdom of the Perl Monks concerning the following question:

Hi all, I how can one force the precise ordering of hash arrays?? i use my $ref = $sth->fetchrow_hashref() to connect and return a table from a database but the above statement does not return the data in the orderd way which it was stored within the database.

Replies are listed 'Best First'.
Re: Order of HASH ARRAYS
by Corion (Patriarch) on Apr 02, 2006 at 18:02 UTC

    In your question it is not clear, which order you want, the order of the hash keys retrieved from the database, or the order of records from the database. As it is, that doesn't matter, because neither has an order.

    If you want an order on the hash keys, you have to define it yourself when outputting your data.

    If you want an order in the records as they are returned from the database, you have to supply the appropriate ORDER BY clause to your SQL.

    If you show us the relevant code, and the output you get, maybe we can give you more exact help.

Re: Oder of HASH ARRAYS
by liverpole (Monsignor) on Apr 02, 2006 at 20:08 UTC
    To expand somewhat on Corion's reply, let's say you have a mysql database called 'new', and a table 'employee', which looks like this:
    mysql> select * from employee; +----+---------+--------+------------+ | id | name | salary | hiredate | +----+---------+--------+------------+ | 1 | Fran | 100000 | 2006-05-01 | | 2 | Barry | 90000 | 2006-04-01 | | 3 | Anna | 80000 | 2006-01-01 | | 4 | Cynthia | 70000 | 2006-02-01 | | 5 | Enrico | 60000 | 2006-03-01 | | 6 | Derek | 50000 | 2006-06-01 | +----+---------+--------+------------+ 6 rows in set (0.00 sec)

    s''(q.S:$/9=(T1';s;(..)(..);$..=substr+crypt($1,$2),2,3;eg;print$..$/
Re: Oder of HASH ARRAYS
by TedPride (Priest) on Apr 02, 2006 at 23:58 UTC
    If you want the data in a specific order, then specify the order in the SELECT and ask for the result as an array:

    SELECT field1, field2, etc. FROM...

    Alternatively, SELECT * will return the data in the order the fields are stored in the table, but again, you need to ask for the results as an array rather than a hash. fetchrow_hashref() is not something I personally find terribly useful.