12 # these shouldn't hang
15 sort { for ($_ = 0;; $_++) {} } @a;
16 sort { while(1) {} } @a;
17 sort { while(1) { last; } } @a;
18 sort { while(0) { last; } } @a;
20 # Change 26011: Re: A surprising segfault
21 map scalar(sort(+())), ('')x68;
24 sub Backwards { $a lt $b ? 1 : $a gt $b ? -1 : 0 }
25 sub Backwards_stacked($$) { my($a,$b) = @_; $a lt $b ? 1 : $a gt $b ? -1 : 0 }
26 sub Backwards_other { $a lt $b ? 1 : $a gt $b ? -1 : 0 }
28 my $upperfirst = 'A' lt 'a';
30 # Beware: in future this may become hairier because of possible
31 # collation complications: qw(A a B b) can be sorted at least as
32 # any of the following
39 # All the above orders make sense.
41 # That said, EBCDIC sorts all small letters first, as opposed
42 # to ASCII which sorts all big letters first.
44 @harry = ('dog','cat','x','Cain','Abel');
45 @george = ('gone','chased','yz','punished','Axed');
47 $x = join('', sort @harry);
48 $expected = $upperfirst ? 'AbelCaincatdogx' : 'catdogxAbelCain';
50 cmp_ok($x,'eq',$expected,'upper first 1');
52 $x = join('', sort( Backwards @harry));
53 $expected = $upperfirst ? 'xdogcatCainAbel' : 'CainAbelxdogcat';
55 cmp_ok($x,'eq',$expected,'upper first 2');
57 $x = join('', sort( Backwards_stacked @harry));
58 $expected = $upperfirst ? 'xdogcatCainAbel' : 'CainAbelxdogcat';
60 cmp_ok($x,'eq',$expected,'upper first 3');
62 $x = join('', sort @george, 'to', @harry);
63 $expected = $upperfirst ?
64 'AbelAxedCaincatchaseddoggonepunishedtoxyz' :
65 'catchaseddoggonepunishedtoxyzAbelAxedCain' ;
67 my @initially_sorted = ( 0 .. 260,
70 0x3FFF, 0x4000, 0x4001,
71 0xFFFF, 0x10000, 0x10001,
73 # It makes things easier below if there are an even number of elements in the
75 if (scalar(@initially_sorted) % 2 == 1) {
76 push @initially_sorted, $initially_sorted[-1] + 1;
79 # We convert to a chr(), but prepend a constant string to make sure things can
80 # work on more than a single character.
82 my $prefix_len = length $prefix;
84 my @chr_initially_sorted = @initially_sorted;
85 $_ = $prefix . chr($_) for @chr_initially_sorted;
87 # Create a very unsorted version by reversing it, and then pushing the same
88 # code points again, but pair-wise reversed.
89 my @initially_unsorted = reverse @chr_initially_sorted;
90 for (my $i = 0; $i < @chr_initially_sorted - 1; $i += 2) {
91 push @initially_unsorted, $chr_initially_sorted[$i+1],
92 $chr_initially_sorted[$i];
95 # And, an all-UTF-8 version
96 my @utf8_initialy_unsorted = @initially_unsorted;
97 utf8::upgrade($_) for @utf8_initialy_unsorted;
99 # Sort the non-UTF-8 version
100 my @non_utf8_result = sort @initially_unsorted;
102 my $ordered_correctly = 1;
103 for my $i (0 .. @chr_initially_sorted -1) {
104 if ( $chr_initially_sorted[$i] ne $non_utf8_result[2*$i]
105 || $chr_initially_sorted[$i] ne $non_utf8_result[2*$i+1])
107 $ordered_correctly = 0;
110 push @wrongly_utf8, $i if $i < 256 && utf8::is_utf8($non_utf8_result[$i]);
112 if (! ok($ordered_correctly, "sort of non-utf8 list worked")) {
113 diag ("This should be in numeric order (with 2 instances of every code point):\n"
114 . join " ", map { sprintf "%02x", ord substr $_, $prefix_len, 1 } @non_utf8_result);
116 if (! is(@wrongly_utf8, 0,
117 "No elements were wrongly converted to utf8 in sorting"))
119 diag "For code points " . join " ", @wrongly_utf8;
122 # And then the UTF-8 one
123 my @wrongly_non_utf8;
124 $ordered_correctly = 1;
125 my @utf8_result = sort @utf8_initialy_unsorted;
126 for my $i (0 .. @chr_initially_sorted -1) {
127 if ( $chr_initially_sorted[$i] ne $utf8_result[2*$i]
128 || $chr_initially_sorted[$i] ne $utf8_result[2*$i+1])
130 $ordered_correctly = 0;
133 push @wrongly_non_utf8, $i unless utf8::is_utf8($utf8_result[$i]);
135 if (! ok($ordered_correctly, "sort of utf8 list worked")) {
136 diag ("This should be in numeric order (with 2 instances of every code point):\n"
137 . join " ", map { sprintf "%02x", ord substr $_, $prefix_len, 1 } @utf8_result);
139 if (! is(@wrongly_non_utf8, 0,
140 "No elements were wrongly converted from utf8 in sorting"))
142 diag "For code points " . join " ", @wrongly_non_utf8;
145 cmp_ok($x,'eq',$expected,'upper first 4');
149 cmp_ok("@b",'eq',"",'reverse 1');
153 cmp_ok("@b",'eq',"1",'reverse 2');
157 cmp_ok("@b",'eq',"2 1",'reverse 3');
161 cmp_ok("@b",'eq',"3 2 1",'reverse 4');
165 cmp_ok("@b",'eq',"4 3 2 1",'reverse 5');
168 @b = sort {$a <=> $b;} @a;
169 cmp_ok("@b",'eq',"2 3 4 10",'sort numeric');
172 $x = join('', sort $sub @harry);
173 $expected = $upperfirst ? 'xdogcatCainAbel' : 'CainAbelxdogcat';
175 cmp_ok($x,'eq',$expected,'sorter sub name in var 1');
177 $sub = 'Backwards_stacked';
178 $x = join('', sort $sub @harry);
179 $expected = $upperfirst ? 'xdogcatCainAbel' : 'CainAbelxdogcat';
181 cmp_ok($x,'eq',$expected,'sorter sub name in var 2');
183 # literals, combinations
186 cmp_ok("@b",'eq','1 2 3 4','just sort');
189 @b = sort grep { $_ } (4,1,3,2);
190 cmp_ok("@b",'eq','1 2 3 4','grep then sort');
193 @b = sort map { $_ } (4,1,3,2);
194 cmp_ok("@b",'eq','1 2 3 4','map then sort');
197 @b = sort reverse (4,1,3,2);
198 cmp_ok("@b",'eq','1 2 3 4','reverse then sort');
201 @b = sort CORE::reverse (4,1,3,2);
202 cmp_ok("@b",'eq','1 2 3 4','CORE::reverse then sort');
204 eval { @b = sort CORE::revers (4,1,3,2); };
205 like($@, qr/^Undefined sort subroutine "CORE::revers" called at /);
208 sub twoface { no warnings 'redefine'; *twoface = sub { $a <=> $b }; &twoface }
209 eval { @b = sort twoface 4,1,3,2 };
210 cmp_ok("@b",'eq','1 2 3 4','redefine sort sub inside the sort sub');
213 eval { no warnings 'redefine'; *twoface = sub { &Backwards } };
214 ok(!$@,"redefining sort subs outside the sort \$@=[$@]");
216 eval { @b = sort twoface 4,1,3,2 };
217 cmp_ok("@b",'eq','4 3 2 1','twoface redefinition');
220 no warnings 'redefine';
221 *twoface = sub { *twoface = *Backwards_other; $a <=> $b };
224 eval { @b = sort twoface 4,1,9,5 };
225 ok(($@ eq "" && "@b" eq "1 4 5 9"),'redefinition should not take effect during the sort');
228 no warnings 'redefine';
230 eval 'sub twoface { $a <=> $b }';
231 die($@ eq "" ? "good\n" : "bad\n");
235 eval { @b = sort twoface 4,1 };
236 cmp_ok(substr($@,0,4), 'eq', 'good', 'twoface eval');
239 my @result = sort main'Backwards 'one', 'two';
241 cmp_ok($@,'eq','',q(old skool package));
244 # "sort 'one', 'two'" should not try to parse "'one" as a sort sub
245 my @result = sort 'one', 'two';
247 cmp_ok($@,'eq','',q(one is not a sub));
250 my $sortsub = \&Backwards;
251 my $sortglob = *Backwards;
252 my $sortglobr = \*Backwards;
253 my $sortname = 'Backwards';
254 @b = sort $sortsub 4,1,3,2;
255 cmp_ok("@b",'eq','4 3 2 1','sortname 1');
256 @b = sort $sortglob 4,1,3,2;
257 cmp_ok("@b",'eq','4 3 2 1','sortname 2');
258 @b = sort $sortname 4,1,3,2;
259 cmp_ok("@b",'eq','4 3 2 1','sortname 3');
260 @b = sort $sortglobr 4,1,3,2;
261 cmp_ok("@b",'eq','4 3 2 1','sortname 4');
265 my $sortsub = \&Backwards_stacked;
266 my $sortglob = *Backwards_stacked;
267 my $sortglobr = \*Backwards_stacked;
268 my $sortname = 'Backwards_stacked';
269 @b = sort $sortsub 4,1,3,2;
270 cmp_ok("@b",'eq','4 3 2 1','sortname 5');
271 @b = sort $sortglob 4,1,3,2;
272 cmp_ok("@b",'eq','4 3 2 1','sortname 6');
273 @b = sort $sortname 4,1,3,2;
274 cmp_ok("@b",'eq','4 3 2 1','sortname 7');
275 @b = sort $sortglobr 4,1,3,2;
276 cmp_ok("@b",'eq','4 3 2 1','sortname 8');
280 local $sortsub = \&Backwards;
281 local $sortglob = *Backwards;
282 local $sortglobr = \*Backwards;
283 local $sortname = 'Backwards';
284 @b = sort $sortsub 4,1,3,2;
285 cmp_ok("@b",'eq','4 3 2 1','sortname local 1');
286 @b = sort $sortglob 4,1,3,2;
287 cmp_ok("@b",'eq','4 3 2 1','sortname local 2');
288 @b = sort $sortname 4,1,3,2;
289 cmp_ok("@b",'eq','4 3 2 1','sortname local 3');
290 @b = sort $sortglobr 4,1,3,2;
291 cmp_ok("@b",'eq','4 3 2 1','sortname local 4');
295 local $sortsub = \&Backwards_stacked;
296 local $sortglob = *Backwards_stacked;
297 local $sortglobr = \*Backwards_stacked;
298 local $sortname = 'Backwards_stacked';
299 @b = sort $sortsub 4,1,3,2;
300 cmp_ok("@b",'eq','4 3 2 1','sortname local 5');
301 @b = sort $sortglob 4,1,3,2;
302 cmp_ok("@b",'eq','4 3 2 1','sortname local 6');
303 @b = sort $sortname 4,1,3,2;
304 cmp_ok("@b",'eq','4 3 2 1','sortname local 7');
305 @b = sort $sortglobr 4,1,3,2;
306 cmp_ok("@b",'eq','4 3 2 1','sortname local 8');
309 ## exercise sort builtins... ($a <=> $b already tested)
310 @a = ( 5, 19, 1996, 255, 90 );
312 my $dummy; # force blockness
315 cmp_ok("@b",'eq','1996 255 90 19 5','force blockness');
317 $x = join('', sort { $a cmp $b } @harry);
318 $expected = $upperfirst ? 'AbelCaincatdogx' : 'catdogxAbelCain';
319 cmp_ok($x,'eq',$expected,'a cmp b');
321 $x = join('', sort { $b cmp $a } @harry);
322 $expected = $upperfirst ? 'xdogcatCainAbel' : 'CainAbelxdogcat';
323 cmp_ok($x,'eq',$expected,'b cmp a');
327 @b = sort { $a <=> $b } @a;
328 cmp_ok("@b",'eq','5 19 90 255 1996','integer a <=> b');
330 @b = sort { $b <=> $a } @a;
331 cmp_ok("@b",'eq','1996 255 90 19 5','integer b <=> a');
333 $x = join('', sort { $a cmp $b } @harry);
334 $expected = $upperfirst ? 'AbelCaincatdogx' : 'catdogxAbelCain';
335 cmp_ok($x,'eq',$expected,'integer a cmp b');
337 $x = join('', sort { $b cmp $a } @harry);
338 $expected = $upperfirst ? 'xdogcatCainAbel' : 'CainAbelxdogcat';
339 cmp_ok($x,'eq',$expected,'integer b cmp a');
345 $x = join('', sort { $a <=> $b } 3, 1, 2);
346 cmp_ok($x,'eq','123',q(optimized-away comparison block doesn't take any other arguments away with it));
348 # test sorting in non-main package
351 @a = ( 5, 19, 1996, 255, 90 );
352 @b = sort { $b <=> $a } @a;
353 ::cmp_ok("@b",'eq','1996 255 90 19 5','not in main:: 1');
355 @b = sort ::Backwards_stacked @a;
356 ::cmp_ok("@b",'eq','90 5 255 1996 19','not in main:: 2');
358 # check if context for sort arguments is handled right
360 my $gimme = wantarray;
361 ::is($gimme,1,'wantarray 1');
363 my $m = sub { $a <=> $b };
365 sub cxt_one { sort $m test_if_list() }
367 sub cxt_two { sort { $a <=> $b } test_if_list() }
369 sub cxt_three { sort &test_if_list() }
371 sub cxt_three_anna_half { sort 0, test_if_list() }
372 cxt_three_anna_half();
375 my $gimme = wantarray;
376 ::is(!($gimme or !defined($gimme)),1,'wantarray 2');
379 $m = \&test_if_scalar;
380 sub cxt_four { sort $m 1,2 }
382 sub cxt_five { sort { test_if_scalar($a,$b); } 1,2 }
384 sub cxt_six { sort test_if_scalar 1,2 }
389 # test against a reentrancy bug
392 sub compare { $a cmp $b }
393 sub reenter { my @force = sort compare qw/a b/ }
396 my($def, $init) = (0, 0);
398 $def = 1 if defined $Bar::a;
399 Bar::reenter() unless $init++;
402 cmp_ok("@b",'eq','1 2 3 4','reenter 1');
404 ok(!$def,'reenter 2');
409 sub routine { "one", "two" };
410 @a = sort(routine(1));
411 cmp_ok("@a",'eq',"one two",'bug id 19991001.003 (#1549)');
415 # check for in-place optimisation of @a = sort @a
419 @g = (3,2,1); $r1 = \$g[2]; @g = sort @g; $r2 = \$g[0];
420 is "$$r1-$$r2-@g", "1-1-1 2 3", "inplace sort of global";
422 @a = qw(b a c); $r1 = \$a[1]; @a = sort @a; $r2 = \$a[0];
423 is "$$r1-$$r2-@a", "a-a-a b c", "inplace sort of lexical";
425 @g = (2,3,1); $r1 = \$g[1]; @g = sort { $b <=> $a } @g; $r2 = \$g[0];
426 is "$$r1-$$r2-@g", "3-3-3 2 1", "inplace reversed sort of global";
429 $r1 = \$g[1]; @g = sort { $a<$b?1:$a>$b?-1:0 } @g; $r2 = \$g[0];
430 is "$$r1-$$r2-@g", "3-3-3 2 1", "inplace custom sort of global";
432 sub mysort { $b cmp $a };
433 @a = qw(b c a); $r1 = \$a[1]; @a = sort mysort @a; $r2 = \$a[0];
434 is "$$r1-$$r2-@a", "c-c-c b a", "inplace sort with function of lexical";
438 tie @t, 'Tie::StdArray';
440 @t = qw(b c a); @t = sort @t;
441 is "@t", "a b c", "inplace sort of tied array";
443 @t = qw(b c a); @t = sort mysort @t;
444 is "@t", "c b a", "inplace sort of tied array with function";
446 # [perl #29790] don't optimise @a = ('a', sort @a) !
448 @g = (3,2,1); @g = ('0', sort @g);
449 is "@g", "0 1 2 3", "un-inplace sort of global";
450 @g = (3,2,1); @g = (sort(@g),'4');
451 is "@g", "1 2 3 4", "un-inplace sort of global 2";
453 @a = qw(b a c); @a = ('x', sort @a);
454 is "@a", "x a b c", "un-inplace sort of lexical";
455 @a = qw(b a c); @a = ((sort @a), 'x');
456 is "@a", "a b c x", "un-inplace sort of lexical 2";
458 @g = (2,3,1); @g = ('0', sort { $b <=> $a } @g);
459 is "@g", "0 3 2 1", "un-inplace reversed sort of global";
460 @g = (2,3,1); @g = ((sort { $b <=> $a } @g),'4');
461 is "@g", "3 2 1 4", "un-inplace reversed sort of global 2";
463 @g = (2,3,1); @g = ('0', sort { $a<$b?1:$a>$b?-1:0 } @g);
464 is "@g", "0 3 2 1", "un-inplace custom sort of global";
465 @g = (2,3,1); @g = ((sort { $a<$b?1:$a>$b?-1:0 } @g),'4');
466 is "@g", "3 2 1 4", "un-inplace custom sort of global 2";
468 @a = qw(b c a); @a = ('x', sort mysort @a);
469 is "@a", "x c b a", "un-inplace sort with function of lexical";
470 @a = qw(b c a); @a = ((sort mysort @a),'x');
471 is "@a", "c b a x", "un-inplace sort with function of lexical 2";
473 # RT#54758. Git 62b40d2474e7487e6909e1872b6bccdf812c6818
475 my @m; push @m, 0 for 1 .. 1024; $#m; @m = sort @m;
476 ::pass("in-place sorting segfault");
478 # RT #39358 - array should be preserved during sort
483 @aa = sort { @copy = @aa; $a cmp $b } @aa;
484 is "@aa", "a b c", "RT 39358 - aa";
485 is "@copy", "b c a", "RT 39358 - copy";
488 # RT #128340: in-place sort incorrectly preserves element lvalue identity
492 @a = sort { $a <=> $b } @a;
494 is ("@a", "3 4 5", "RT #128340");
498 # Test optimisations of reversed sorts. As we now guarantee stability by
499 # default, # optimisations which do not provide this are bogus.
503 use overload (qw("" stringify 0+ numify fallback 1));
506 bless [$_[1], $_[2]], $_[0];
509 sub stringify { $_[0]->[0] }
511 sub numify { $_[0]->[1] }
516 map {new Oscalar $_, $count++} qw(A A A B B B C C C);
519 my @input = &generate;
520 my @output = sort @input;
521 is join(" ", map {0+$_} @output), "0 1 2 3 4 5 6 7 8", "Simple stable sort";
524 @input = sort @input;
525 is join(" ", map {0+$_} @input), "0 1 2 3 4 5 6 7 8",
526 "Simple stable in place sort";
528 # This won't be very interesting
530 @output = sort {$a <=> $b} @input;
531 is "@output", "A A A B B B C C C", 'stable $a <=> $b sort';
534 @output = sort {$a cmp $b} @input;
535 is join(" ", map {0+$_} @output), "0 1 2 3 4 5 6 7 8", 'stable $a cmp $b sort';
538 @input = sort {$a cmp $b} @input;
539 is join(" ", map {0+$_} @input), "0 1 2 3 4 5 6 7 8",
540 'stable $a cmp $b in place sort';
543 @output = sort {$b cmp $a} @input;
544 is join(" ", map {0+$_} @output), "6 7 8 3 4 5 0 1 2", 'stable $b cmp $a sort';
547 @input = sort {$b cmp $a} @input;
548 is join(" ", map {0+$_} @input), "6 7 8 3 4 5 0 1 2",
549 'stable $b cmp $a in place sort';
552 @output = reverse sort @input;
553 is join(" ", map {0+$_} @output), "8 7 6 5 4 3 2 1 0", "Reversed stable sort";
556 @input = reverse sort @input;
557 is join(" ", map {0+$_} @input), "8 7 6 5 4 3 2 1 0",
558 "Reversed stable in place sort";
561 my $output = reverse sort @input;
562 is $output, "CCCBBBAAA", "Reversed stable sort in scalar context";
566 @output = reverse sort {$a cmp $b} @input;
567 is join(" ", map {0+$_} @output), "8 7 6 5 4 3 2 1 0",
568 'reversed stable $a cmp $b sort';
571 @input = reverse sort {$a cmp $b} @input;
572 is join(" ", map {0+$_} @input), "8 7 6 5 4 3 2 1 0",
573 'revesed stable $a cmp $b in place sort';
576 $output = reverse sort {$a cmp $b} @input;
577 is $output, "CCCBBBAAA", 'Reversed stable $a cmp $b sort in scalar context';
580 @output = reverse sort {$b cmp $a} @input;
581 is join(" ", map {0+$_} @output), "2 1 0 5 4 3 8 7 6",
582 'reversed stable $b cmp $a sort';
585 @input = reverse sort {$b cmp $a} @input;
586 is join(" ", map {0+$_} @input), "2 1 0 5 4 3 8 7 6",
587 'revesed stable $b cmp $a in place sort';
590 $output = reverse sort {$b cmp $a} @input;
591 is $output, "AAABBBCCC", 'Reversed stable $b cmp $a sort in scalar context';
594 # Something complex enough to defeat any constant folding optimiser
599 @output = reverse sort {stuff || $a cmp $b} @input;
600 is join(" ", map {0+$_} @output), "8 7 6 5 4 3 2 1 0",
601 'reversed stable complex sort';
604 @input = reverse sort {stuff || $a cmp $b} @input;
605 is join(" ", map {0+$_} @input), "8 7 6 5 4 3 2 1 0",
606 'revesed stable complex in place sort';
609 $output = reverse sort {stuff || $a cmp $b } @input;
610 is $output, "CCCBBBAAA", 'Reversed stable complex sort in scalar context';
616 @output = sortr &generate;
617 is join(" ", map {0+$_} @output), "8 7 6 5 4 3 2 1 0",
618 'reversed stable sort return list context';
619 $output = sortr &generate;
620 is $output, "CCCBBBAAA",
621 'reversed stable sort return scalar context';
624 reverse sort {$a cmp $b} @_;
627 @output = sortcmpr &generate;
628 is join(" ", map {0+$_} @output), "8 7 6 5 4 3 2 1 0",
629 'reversed stable $a cmp $b sort return list context';
630 $output = sortcmpr &generate;
631 is $output, "CCCBBBAAA",
632 'reversed stable $a cmp $b sort return scalar context';
635 reverse sort {$b cmp $a} @_;
638 @output = sortcmprba &generate;
639 is join(" ", map {0+$_} @output), "2 1 0 5 4 3 8 7 6",
640 'reversed stable $b cmp $a sort return list context';
641 $output = sortcmprba &generate;
642 is $output, "AAABBBCCC",
643 'reversed stable $b cmp $a sort return scalar context';
646 reverse sort {stuff || $a cmp $b} @_;
649 @output = sortcmpr &generate;
650 is join(" ", map {0+$_} @output), "8 7 6 5 4 3 2 1 0",
651 'reversed stable complex sort return list context';
652 $output = sortcmpr &generate;
653 is $output, "CCCBBBAAA",
654 'reversed stable complex sort return scalar context';
656 # And now with numbers
660 map {new Oscalar $count++, $_} 0, 0, 0, 1, 1, 1, 2, 2, 2;
663 # This won't be very interesting
665 @output = sort {$a cmp $b} @input;
666 is "@output", "A B C D E F G H I", 'stable $a cmp $b sort';
669 @output = sort {$a <=> $b} @input;
670 is "@output", "A B C D E F G H I", 'stable $a <=> $b sort';
673 @input = sort {$a <=> $b} @input;
674 is "@input", "A B C D E F G H I", 'stable $a <=> $b in place sort';
677 @output = sort {$b <=> $a} @input;
678 is "@output", "G H I D E F A B C", 'stable $b <=> $a sort';
681 @input = sort {$b <=> $a} @input;
682 is "@input", "G H I D E F A B C", 'stable $b <=> $a in place sort';
684 # test that optimized {$b cmp $a} and {$b <=> $a} remain stable
685 # (new in 5.9) without overloading
687 @b = sort { $b <=> $a } @input = qw/5first 6first 5second 6second/;
688 is "@b" , "6first 6second 5first 5second", "optimized {$b <=> $a} without overloading" ;
689 @input = sort {$b <=> $a} @input;
690 is "@input" , "6first 6second 5first 5second","inline optimized {$b <=> $a} without overloading" ;
693 # These two are actually doing string cmp on 0 1 and 2
695 @output = reverse sort @input;
696 is "@output", "I H G F E D C B A", "Reversed stable sort";
699 @input = reverse sort @input;
700 is "@input", "I H G F E D C B A", "Reversed stable in place sort";
703 $output = reverse sort @input;
704 is $output, "IHGFEDCBA", "Reversed stable sort in scalar context";
707 @output = reverse sort {$a <=> $b} @input;
708 is "@output", "I H G F E D C B A", 'reversed stable $a <=> $b sort';
711 @input = reverse sort {$a <=> $b} @input;
712 is "@input", "I H G F E D C B A", 'revesed stable $a <=> $b in place sort';
715 $output = reverse sort {$a <=> $b} @input;
716 is $output, "IHGFEDCBA", 'reversed stable $a <=> $b sort in scalar context';
719 @output = reverse sort {$b <=> $a} @input;
720 is "@output", "C B A F E D I H G", 'reversed stable $b <=> $a sort';
723 @input = reverse sort {$b <=> $a} @input;
724 is "@input", "C B A F E D I H G", 'revesed stable $b <=> $a in place sort';
727 $output = reverse sort {$b <=> $a} @input;
728 is $output, "CBAFEDIHG", 'reversed stable $b <=> $a sort in scalar context';
731 @output = reverse sort {stuff || $a <=> $b} @input;
732 is "@output", "I H G F E D C B A", 'reversed stable complex sort';
735 @input = reverse sort {stuff || $a <=> $b} @input;
736 is "@input", "I H G F E D C B A", 'revesed stable complex in place sort';
739 $output = reverse sort {stuff || $a <=> $b} @input;
740 is $output, "IHGFEDCBA", 'reversed stable complex sort in scalar context';
743 reverse sort {$a <=> $b} @_;
746 @output = sortnumr &generate1;
747 is "@output", "I H G F E D C B A",
748 'reversed stable $a <=> $b sort return list context';
749 $output = sortnumr &generate1;
750 is $output, "IHGFEDCBA", 'reversed stable $a <=> $b sort return scalar context';
753 reverse sort {$b <=> $a} @_;
756 @output = sortnumrba &generate1;
757 is "@output", "C B A F E D I H G",
758 'reversed stable $b <=> $a sort return list context';
759 $output = sortnumrba &generate1;
760 is $output, "CBAFEDIHG", 'reversed stable $b <=> $a sort return scalar context';
763 reverse sort {stuff || $a <=> $b} @_;
766 @output = sortnumrq &generate1;
767 is "@output", "I H G F E D C B A",
768 'reversed stable complex sort return list context';
769 $output = sortnumrq &generate1;
770 is $output, "IHGFEDCBA", 'reversed stable complex sort return scalar context';
772 @output = reverse (sort(qw(C A B)), 0);
773 is "@output", "0 C B A", 'reversed sort with trailing argument';
775 @output = reverse (0, sort(qw(C A B)));
776 is "@output", "C B A 0", 'reversed sort with leading argument';
778 eval { @output = sort {goto sub {}} 1,2; };
779 $fail_msg = q(Can't goto subroutine outside a subroutine);
780 cmp_ok(substr($@,0,length($fail_msg)),'eq',$fail_msg,'goto subr outside subr');
784 sub goto_sub {goto sub{}}
785 eval { @output = sort goto_sub 1,2; };
786 $fail_msg = q(Can't goto subroutine from a sort sub);
787 cmp_ok(substr($@,0,length($fail_msg)),'eq',$fail_msg,'goto subr from a sort sub');
791 eval { @output = sort {goto label} 1,2; };
792 $fail_msg = q(Can't "goto" out of a pseudo block);
793 cmp_ok(substr($@,0,length($fail_msg)),'eq',$fail_msg,'goto out of a pseudo block 1');
797 sub goto_label {goto label}
798 label: eval { @output = sort goto_label 1,2; };
799 $fail_msg = q(Can't "goto" out of a pseudo block);
800 cmp_ok(substr($@,0,length($fail_msg)),'eq',$fail_msg,'goto out of a pseudo block 2');
804 sub self_immolate {undef &self_immolate; $a<=>$b}
805 eval { @output = sort self_immolate 1,2,3 };
806 $fail_msg = q(Can't undef active subroutine);
807 cmp_ok(substr($@,0,length($fail_msg)),'eq',$fail_msg,'undef active subr');
810 for(1,2) # We run this twice, to make sure sort does not lower the ref
811 { # count. See bug 71076.
816 if (!defined($n)) { # No arg means we're being called by sort()
819 if ($n<5) { rec($n+1); }
820 else { () = sort rec 1,2; }
822 $failed = 1 if !defined $n;
826 ok(!$failed, "sort from active sub");
829 # $a and $b are set in the package the sort() is called from,
830 # *not* the package the sort sub is in. This is longstanding
831 # de facto behaviour that shouldn't be broken.
833 () = sort OtherPack::foo 1,2,3,4;
839 $answer = "something was unexpectedly defined or undefined" if
840 defined($a) || defined($b) || !defined($main::a) || !defined($main::b);
841 $main::a <=> $main::b;
845 cmp_ok($answer,'eq','good','sort subr called from other package');
848 # Bug 36430 - sort called in package2 while a
849 # sort in package1 is active should set $package2::a/b.
852 my @list = sort { A::min(@$a) <=> A::min(@$b) }
853 [3, 1, 5], [2, 4], [0];
855 cmp_ok($answer,'eq','good','bug 36430');
860 $answer = '$a and/or $b are not defined ' if !defined($a) || !defined($b);
869 # I commented out this TODO test because messing with FREEd scalars on the
870 # stack can have all sorts of strange side-effects, not made safe by eval
874 # local $TODO = "sort should make sure elements are not freed in the sort block";
875 # eval { @nomodify_x=(1..8);
876 # our @copy = sort { undef @nomodify_x; 1 } (@nomodify_x, 3); };
881 # Sorting shouldn't increase the refcount of a sub
883 sub sportello {(1+$a) <=> (1+$b)}
884 my $refcnt = &Internals::SvREFCNT(\&sportello);
885 @output = sort sportello 3,7,9;
889 ::is($refcnt, &Internals::SvREFCNT(\&::sportello), "sort sub refcnt");
890 $fail_msg = q(Modification of a read-only value attempted);
891 # Sorting a read-only array in-place shouldn't be allowed
892 my @readonly = (1..10);
893 Internals::SvREADONLY(@readonly, 1);
894 eval { @readonly = sort @readonly; };
895 ::cmp_ok(substr($@,0,length($fail_msg)),'eq',$fail_msg,'in-place sort of read-only array');
900 # Using return() should be okay even in a deeper context
901 @b = sort {while (1) {return ($a <=> $b)} } 1..10;
902 is("@b", "1 2 3 4 5 6 7 8 9 10", "return within loop");
904 # Using return() should be okay even if there are other items
905 # on the stack at the time.
906 @b = sort {$_ = ($a<=>$b) + do{return $b<=> $a}} 1..10;
907 is("@b", "10 9 8 7 6 5 4 3 2 1", "return with SVs on stack");
909 # As above, but with a sort sub rather than a sort block.
910 sub ret_with_stacked { $_ = ($a<=>$b) + do {return $b <=> $a} }
911 @b = sort ret_with_stacked 1..10;
912 is("@b", "10 9 8 7 6 5 4 3 2 1", "return with SVs on stack");
914 # Comparison code should be able to give result in non-integer representation.
915 sub cmp_as_string($$) { $_[0] < $_[1] ? "-1" : $_[0] == $_[1] ? "0" : "+1" }
916 @b = sort { cmp_as_string($a, $b) } (1,5,4,7,3,2,3);
917 is("@b", "1 2 3 3 4 5 7", "comparison result as string");
918 @b = sort cmp_as_string (1,5,4,7,3,2,3);
919 is("@b", "1 2 3 3 4 5 7", "comparison result as string");
921 # RT #34604: sort didn't honour overloading if the overloaded elements
922 # were retrieved via tie
927 sub TIEHASH { bless {
928 p => bless({ val => 2 }),
929 q => bless({ val => 1 }),
932 sub FETCH { $_[0]{$_[1] } }
935 sub compare { $cc++; $_[0]{val} cmp $_[1]{val} }
937 sub str { $cs++; $_[0]{val} }
939 use overload 'cmp' => \&compare, '""' => \&str;
943 tie my %h, 'RT34604';
944 my @sorted = sort @h{qw(p q)};
945 is($cc, 1, 'overload compare called once');
946 is("@sorted","1 2", 'overload sort result');
947 is($cs, 2, 'overload string called twice');
950 fresh_perl_is('sub w ($$) {my ($l, $r) = @_; my $v = \@_; undef @_; $l <=> $r}; print join q{ }, sort w 3, 1, 2, 0',
952 {stderr => 1, switches => ['-w']},
955 fresh_perl_is('sub w ($$) {my ($l, $r) = @_; my $v = \@_; undef @_; @_ = 0..2; $l <=> $r}; print join q{ }, sort w 3, 1, 2, 0',
957 {stderr => 1, switches => ['-w']},
981 is($count, 0, 'None before we start');
982 my @a = map { Counter->new() } 0..1;
983 is($count, 2, '2 here');
985 my @b = sort sorter @a;
988 cmp_ok($b[0], '<', $b[1], 'sorted!');
990 is($count, 2, 'still the same 2 here');
994 is($count, 0, 'all gone');
997 # [perl #77930] The context stack may be reallocated during a sort, as a
998 # result of deeply-nested (or not-so-deeply-nested) calls
999 # from a custom sort subroutine.
1003 local $count = $count+1;
1004 ()->$sub if $count < 1000;
1007 () = sort $sub qw<a b c d e f g>;
1012 '[perl #77930] cx_stack reallocation during sort'
1016 # Match vars should not leak from one sort sub call to the next
1021 "Leakage" =~ /(.*)/;
1026 "Leakage" =~ /(.*)/;
1031 my @b = sort soarter 0..2;
1033 like $output, qr/^(?:Win)+\z/,
1034 "Match vars do not leak from one plain sort sub to the next";
1039 @b = sort soarterdd 0..2;
1041 like $output, qr/^(?:Win)+\z/,
1042 'Match vars do not leak from one $$ sort sub to the next';
1045 # [perl #30661] autoloading
1046 AUTOLOAD { $b <=> $a }
1048 is join("", sort stubbedsub split//, '04381091'), '98431100',
1049 'stubborn AUTOLOAD';
1050 is join("", sort hopefullynonexistent split//, '04381091'), '98431100',
1051 'AUTOLOAD without stub';
1052 my $stubref = \&givemeastub;
1053 is join("", sort $stubref split//, '04381091'), '98431100',
1054 'AUTOLOAD with stubref';
1056 # [perl #90030] sort without arguments
1057 eval '@x = (sort); 1';
1058 is $@, '', '(sort) does not die';
1059 is @x, 0, '(sort) returns empty list';
1060 eval '@x = sort; 1';
1061 is $@, '', 'sort; does not die';
1062 is @x, 0, 'sort; returns empty list';
1063 eval '{@x = sort} 1';
1064 is $@, '', '{sort} does not die';
1065 is @x, 0, '{sort} returns empty list';
1067 # this happened while the padrange op was being added. Sort blocks
1068 # are executed in void context, and the padrange op was skipping pushing
1069 # the item in void cx. The net result was that the return value was
1070 # whatever was on the stack last.
1076 undef; # this got returned by mistake
1081 is "@a", "0 1 3 5 6", "padrange and void context";
1084 # Fatal warnings an sort sub returning a non-number
1085 # We need two evals, because the panic used to happen on scope exit.
1086 eval { eval { use warnings FATAL => 'all'; () = sort { undef } 1,2 } };
1088 'no panic/crash with fatal warnings when sort sub returns undef';
1089 eval { eval { use warnings FATAL => 'all'; () = sort { "no thin" } 1,2 } };
1091 'no panic/crash with fatal warnings when sort sub returns string';
1092 sub notdef($$) { undef }
1093 eval { eval { use warnings FATAL => 'all'; () = sort notdef 1,2 } };
1095 'no panic/crash with fatal warnings when sort sub($$) returns undef';
1096 sub yarn($$) { "no thinking aloud" }
1097 eval { eval { use warnings FATAL => 'all'; () = sort yarn 1,2 } };
1099 'no panic/crash with fatal warnings when sort sub($$) returns string';
1102 () = [sort { $a = 10; $b = 10; 0 } $#a, $#a];
1103 is $#a, 10, 'sort block modifying $a and $b';
1106 is \$a, \$a, '[perl #78194] op return values passed to sort'; 0
1107 } "${\''}", "${\''}";
1110 @_=sort { delete $deletions::{a}; delete $deletions::{b}; 3 } 1..3;
1112 pass "no crash when sort block deletes *a and *b";
1114 # make sure return args are always evaluated in scalar context
1120 sub f1 { $b <=> $a, $a <=> $b }
1121 sub f2 { return ($b <=> $a, $a <=> $b) }
1122 sub f3 { for ($b <=> $a) { return ($b <=> $a, $a <=> $b) } }
1125 no warnings 'uninitialized';
1126 ::is (join('-', sort { () } 3,1,2,4), '3-1-2-4', "Ret: null blk");
1128 ::is (join('-', sort { $b <=> $a, $a <=> $b } 3,1,2,4), '1-2-3-4', "Ret: blk");
1129 ::is (join('-', sort { for($b <=> $a) { return ($b <=> $a, $a <=> $b) } }
1130 3,1,2,4), '1-2-3-4', "Ret: blk ret");
1132 no warnings 'uninitialized';
1133 ::is (join('-', sort f0 3,1,2,4), '3-1-2-4', "Ret: f0");
1135 ::is (join('-', sort f1 3,1,2,4), '1-2-3-4', "Ret: f1");
1136 ::is (join('-', sort f2 3,1,2,4), '1-2-3-4', "Ret: f2");
1137 ::is (join('-', sort f3 3,1,2,4), '1-2-3-4', "Ret: f3");
1141 @a = sort{ *a=0; 1} 0..1;
1142 pass "No crash when GP deleted out from under us [perl 124097]";
1144 no warnings 'redefine';
1145 # some alternative non-solutions localized modifications to *a and *b
1147 @a = sort { *a = sub { 1 }; $a <=> $b } 0 .. 1;
1148 ok(a(), "*a wasn't localized inadvertantly");
1153 eval { require Config; 1 }
1154 or skip "Cannot load Config", 1;
1155 $Config::Config{ivsize} == 8
1156 or skip "this test can only fail with 64-bit integers", 1;
1157 # sort's built-in numeric comparison wasn't careful enough in a world
1158 # of integers with more significant digits than NVs
1159 my @in = ( "0", "20000000000000001", "20000000000000000" );
1160 my @out = sort { $a <=> $b } @in;
1161 is($out[1], "20000000000000000", "check sort order");