sort

Usage

sort xpath|perl-code perl-code %id

Description

EXPERIMENTAL! This command is not yet guaranteed to remain in the future releases.

DOCUMENTATION OBSOLETE! Syntax changed!

This command may be used to sort the node-list stored in the node-list variable id. First, for each node in the node-list %id, the first argument (either a xpath or perl-code expression), which serves as a sorting criterion, is evaluated in the context of the node and the obtained value is stored together with the node. (In case of xpath the result of whatever type is cast to a string). Then perl's sorting algorithm is used to sort the nodelist, consulting the second, perl-code, argument to compare nodes. Before the perl-code is evaluated, the values obtained from the previous evaluation of the sorting crierion argument on the two nodes being compared are stored into $a and $b variables in the respective order. The perl-code being consulted is supposed to return either -1 (the first node should come first), 0 (no order precedence), or 1 (the second node should come first). Note that Perl provides very convenient operators cmp and <=> for string and numeric comparison of this kind as shown in the examples below.

Remember that sort (unlike assign, if, or while) evaluates the first xpath argument (the sorting criterion) in a way to obtain a string. Thus you need not to bother with wrapping node-queries with a string() function but you must remember to explicitly wrap the expression in count() if the number of the nodes is to be the sorting criterion.

Example 29. Sort creatures by name (XPath-based sort) in ascending order using current locale settings

xsh> local %c=/middle-earth[1]/creatures
xsh> sort @name { use locale; lc($a) cmp lc($b) } %c
xsh> xmove %c into /middle-earth[1]# replaces the creatures

Example 30. Sort (descending order) a node-list by score (Perl-based sort)

xsh> sort { $scores{ literal('@name') } } { $b <=> $a } %players