1sort(3pm) Perl Programmers Reference Guide sort(3pm)
2
3
4
6 sort - perl pragma to control sort() behaviour
7
9 use sort 'stable'; # guarantee stability
10 use sort 'defaults'; # revert to default behavior
11 no sort 'stable'; # stability not important
12
13 my $current;
14 BEGIN {
15 $current = sort::current(); # identify prevailing pragmata
16 }
17
19 With the "sort" pragma you can control the behaviour of the builtin
20 "sort()" function.
21
22 A stable sort means that for records that compare equal, the original
23 input ordering is preserved. Stability will matter only if elements
24 that compare equal can be distinguished in some other way. That means
25 that simple numerical and lexical sorts do not profit from stability,
26 since equal elements are indistinguishable. However, with a comparison
27 such as
28
29 { substr($a, 0, 3) cmp substr($b, 0, 3) }
30
31 stability might matter because elements that compare equal on the first
32 3 characters may be distinguished based on subsequent characters.
33
34 Whether sorting is stable by default is an accident of implementation
35 that can change (and has changed) between Perl versions. If stability
36 is important, be sure to say so with a
37
38 use sort 'stable';
39
40 The "no sort" pragma doesn't forbid what follows, it just leaves the
41 choice open. Thus, after
42
43 no sort 'stable';
44
45 sorting may happen to be stable anyway.
46
48 As of Perl 5.10, this pragma is lexically scoped and takes effect at
49 compile time. In earlier versions its effect was global and took effect
50 at run-time; the documentation suggested using "eval()" to change the
51 behaviour:
52
53 { eval 'no sort "stable"'; # stability not wanted
54 print sort::current . "\n";
55 @a = sort @b;
56 eval 'use sort "defaults"'; # clean up, for others
57 }
58 { eval 'use sort qw(defaults stable)'; # force stability
59 print sort::current . "\n";
60 @c = sort @d;
61 eval 'use sort "defaults"'; # clean up, for others
62 }
63
64 Such code no longer has the desired effect, for two reasons. Firstly,
65 the use of "eval()" means that the sorting algorithm is not changed
66 until runtime, by which time it's too late to have any effect.
67 Secondly, "sort::current" is also called at run-time, when in fact the
68 compile-time value of "sort::current" is the one that matters.
69
70 So now this code would be written:
71
72 { no sort "stable"; # stability not wanted
73 my $current;
74 BEGIN { $current = sort::current; }
75 print "$current\n";
76 @a = sort @b;
77 # Pragmas go out of scope at the end of the block
78 }
79 { use sort qw(defaults stable); # force stability
80 my $current;
81 BEGIN { $current = sort::current; }
82 print "$current\n";
83 @c = sort @d;
84 }
85
86
87
88perl v5.28.2 2018-11-01 sort(3pm)