Gossamer Forum
Home : General : Perl Programming :

Perl coding question

Quote Reply
Perl coding question
I'm learning Perl. Could someone explain this Dbman's default.cfg (aka db.cfg) code fragment to me? It's located near the very end of the default.cfg module of Dbman.

foreach (sort { $db_def{$a}[0] <=> $db_def{$b}[0] } keys %db_def) { ...<action>...

I'm particularly clueless about the function of the "{ $db_def{$a}[0] <=> $db_def{$b}[0] }" portion. How are {$a} and {$b} used?

Thanks. Jim

PS: db_def is an associative array:

%db_def = (
'f00' => [ 0, 'alpha', 30, 30, 0, '', '', 'owners email' ],
'f01' => [ 1, 'alpha', -2, 10, 0, '', '', 'not used' ]
);



Quote Reply
Re: Perl coding question In reply to
Hi Jim,

When you call sort it defaults to sorting a list alphabetically. If you don't want this, you can pass in your own subroutine which should expect $a, and $b to contain two things to be compared, and it should return 1, 0 or -1 depending on which one is greater.

The code you see takes a list of field names and sorts them based on the contents of the first element of the array.

Hope that helps,

Alex