Core Function Sort
(→flag) |
(→Example) |
||
Line 89: | Line 89: | ||
printr($arr); | printr($arr); | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | // Example of using an operation to sort | ||
+ | <syntaxhighlight lang="sputnik"> | ||
+ | my $arr = array( | ||
+ | "A", | ||
+ | "C", | ||
+ | "b", | ||
+ | "f", | ||
+ | "G", | ||
+ | "e", | ||
+ | "h", | ||
+ | "D" | ||
+ | ); | ||
+ | |||
+ | // Print H to A | ||
+ | my $newarray = sort($arr, 0, $b <=> $a); | ||
+ | printr($newarray); | ||
+ | |||
+ | // Print A to H | ||
+ | my $newarray = sort($arr, 0, $a <=> $b); | ||
+ | printr($newarray); | ||
+ | |||
</syntaxhighlight> | </syntaxhighlight> | ||
[[Category:Core Function]] | [[Category:Core Function]] |
Revision as of 15:40, 11 August 2013
Sort( <array>, <flag>, <function> )
Contents |
Description
Sort an array by value or keys optionally modify it in place or return new and optionally use a custom function to decide how to sort it.
Parameters
array
The array to order.
flag
Optional; The flag which determines how the sort works
Flag 1 = Modify array in place and return only a 1 on success and 0 on failure
Flag 2 = Sort by Keys instead of Values
Flag 4 = Ignore case when sorting (when using only 2 params)
Flag 8 = Compares by evaluating the numeric values of the corresponding Chars in each value/key (when using only 2 params) (Note - Flag 4 is ignored on this setting)
Flag 16 = Include the keys if you are comparing values or include the values if you are comparing keys (When using 3 params)
Default: 0 = Sort by values and do not modify original array instead return a copy
function
Optional; If this parameter exists and contains a valid function it will be used to handle the sort
Return Value
If Flag is 0:
Returns new array on success and empty array on failure
If Flag is 1:
Returns true on success and false on failure
Remarks
If no function is given the sort will be alphabetical
Example
// Example of most basic usage to alphabetically sort by values
my $arr = qw(gg bb aa zz dd ff ee); // Flag 0 default flag my $newarray = sort($arr); printr($newarray);
// Example of basic usage to alphabetically sort by keys
my $arr = array("ZZZ" => "FoX", "AAA" => "Cat", "DDD" => "Frog"); // Flag 0 default flag my $newarray = sort($arr, 2); printr($newarray);
// Example of using a function to sort by values
my $arr = qw(1 2 3 4 5 6 7 8 9); // Flag 0 default flag my $newarray = sort($arr, 0, Function( $a, $b ){ return $a > $b; }); printr($newarray);
// Example of using a function to sort by keys
my $arr = qw(1 2 3 4 5 6 7 8 9); // Flag 1 to no return a new array // Flag 2 to sort by KEYS instead of values sort($arr, 1 | 2, Function( $a, $b ){ return $a > $b; }); printr($arr);
// Example of using an operation to sort
my $arr = array( "A", "C", "b", "f", "G", "e", "h", "D" ); // Print H to A my $newarray = sort($arr, 0, $b <=> $a); printr($newarray); // Print A to H my $newarray = sort($arr, 0, $a <=> $b); printr($newarray);