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-@g", "$r2-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-@a", "$r2-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-@g", "$r2-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-@g", "$r2-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-@a", "$r2-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";
489 # Test optimisations of reversed sorts. As we now guarantee stability by
490 # default, # optimisations which do not provide this are bogus.
494 use overload (qw("" stringify 0+ numify fallback 1));
497 bless [$_[1], $_[2]], $_[0];
500 sub stringify { $_[0]->[0] }
502 sub numify { $_[0]->[1] }
507 map {new Oscalar $_, $count++} qw(A A A B B B C C C);
510 my @input = &generate;
511 my @output = sort @input;
512 is join(" ", map {0+$_} @output), "0 1 2 3 4 5 6 7 8", "Simple stable sort";
515 @input = sort @input;
516 is join(" ", map {0+$_} @input), "0 1 2 3 4 5 6 7 8",
517 "Simple stable in place sort";
519 # This won't be very interesting
521 @output = sort {$a <=> $b} @input;
522 is "@output", "A A A B B B C C C", 'stable $a <=> $b sort';
525 @output = sort {$a cmp $b} @input;
526 is join(" ", map {0+$_} @output), "0 1 2 3 4 5 6 7 8", 'stable $a cmp $b sort';
529 @input = sort {$a cmp $b} @input;
530 is join(" ", map {0+$_} @input), "0 1 2 3 4 5 6 7 8",
531 'stable $a cmp $b in place sort';
534 @output = sort {$b cmp $a} @input;
535 is join(" ", map {0+$_} @output), "6 7 8 3 4 5 0 1 2", 'stable $b cmp $a sort';
538 @input = sort {$b cmp $a} @input;
539 is join(" ", map {0+$_} @input), "6 7 8 3 4 5 0 1 2",
540 'stable $b cmp $a in place sort';
543 @output = reverse sort @input;
544 is join(" ", map {0+$_} @output), "8 7 6 5 4 3 2 1 0", "Reversed stable sort";
547 @input = reverse sort @input;
548 is join(" ", map {0+$_} @input), "8 7 6 5 4 3 2 1 0",
549 "Reversed stable in place sort";
552 my $output = reverse sort @input;
553 is $output, "CCCBBBAAA", "Reversed stable sort in scalar context";
557 @output = reverse sort {$a cmp $b} @input;
558 is join(" ", map {0+$_} @output), "8 7 6 5 4 3 2 1 0",
559 'reversed stable $a cmp $b sort';
562 @input = reverse sort {$a cmp $b} @input;
563 is join(" ", map {0+$_} @input), "8 7 6 5 4 3 2 1 0",
564 'revesed stable $a cmp $b in place sort';
567 $output = reverse sort {$a cmp $b} @input;
568 is $output, "CCCBBBAAA", 'Reversed stable $a cmp $b sort in scalar context';
571 @output = reverse sort {$b cmp $a} @input;
572 is join(" ", map {0+$_} @output), "2 1 0 5 4 3 8 7 6",
573 'reversed stable $b cmp $a sort';
576 @input = reverse sort {$b cmp $a} @input;
577 is join(" ", map {0+$_} @input), "2 1 0 5 4 3 8 7 6",
578 'revesed stable $b cmp $a in place sort';
581 $output = reverse sort {$b cmp $a} @input;
582 is $output, "AAABBBCCC", 'Reversed stable $b cmp $a sort in scalar context';
585 # Something complex enough to defeat any constant folding optimiser
590 @output = reverse sort {stuff || $a cmp $b} @input;
591 is join(" ", map {0+$_} @output), "8 7 6 5 4 3 2 1 0",
592 'reversed stable complex sort';
595 @input = reverse sort {stuff || $a cmp $b} @input;
596 is join(" ", map {0+$_} @input), "8 7 6 5 4 3 2 1 0",
597 'revesed stable complex in place sort';
600 $output = reverse sort {stuff || $a cmp $b } @input;
601 is $output, "CCCBBBAAA", 'Reversed stable complex sort in scalar context';
607 @output = sortr &generate;
608 is join(" ", map {0+$_} @output), "8 7 6 5 4 3 2 1 0",
609 'reversed stable sort return list context';
610 $output = sortr &generate;
611 is $output, "CCCBBBAAA",
612 'reversed stable sort return scalar context';
615 reverse sort {$a cmp $b} @_;
618 @output = sortcmpr &generate;
619 is join(" ", map {0+$_} @output), "8 7 6 5 4 3 2 1 0",
620 'reversed stable $a cmp $b sort return list context';
621 $output = sortcmpr &generate;
622 is $output, "CCCBBBAAA",
623 'reversed stable $a cmp $b sort return scalar context';
626 reverse sort {$b cmp $a} @_;
629 @output = sortcmprba &generate;
630 is join(" ", map {0+$_} @output), "2 1 0 5 4 3 8 7 6",
631 'reversed stable $b cmp $a sort return list context';
632 $output = sortcmprba &generate;
633 is $output, "AAABBBCCC",
634 'reversed stable $b cmp $a sort return scalar context';
637 reverse sort {stuff || $a cmp $b} @_;
640 @output = sortcmpr &generate;
641 is join(" ", map {0+$_} @output), "8 7 6 5 4 3 2 1 0",
642 'reversed stable complex sort return list context';
643 $output = sortcmpr &generate;
644 is $output, "CCCBBBAAA",
645 'reversed stable complex sort return scalar context';
647 # And now with numbers
651 map {new Oscalar $count++, $_} 0, 0, 0, 1, 1, 1, 2, 2, 2;
654 # This won't be very interesting
656 @output = sort {$a cmp $b} @input;
657 is "@output", "A B C D E F G H I", 'stable $a cmp $b sort';
660 @output = sort {$a <=> $b} @input;
661 is "@output", "A B C D E F G H I", 'stable $a <=> $b sort';
664 @input = sort {$a <=> $b} @input;
665 is "@input", "A B C D E F G H I", 'stable $a <=> $b in place sort';
668 @output = sort {$b <=> $a} @input;
669 is "@output", "G H I D E F A B C", 'stable $b <=> $a sort';
672 @input = sort {$b <=> $a} @input;
673 is "@input", "G H I D E F A B C", 'stable $b <=> $a in place sort';
675 # test that optimized {$b cmp $a} and {$b <=> $a} remain stable
676 # (new in 5.9) without overloading
678 @b = sort { $b <=> $a } @input = qw/5first 6first 5second 6second/;
679 is "@b" , "6first 6second 5first 5second", "optimized {$b <=> $a} without overloading" ;
680 @input = sort {$b <=> $a} @input;
681 is "@input" , "6first 6second 5first 5second","inline optimized {$b <=> $a} without overloading" ;
684 # These two are actually doing string cmp on 0 1 and 2
686 @output = reverse sort @input;
687 is "@output", "I H G F E D C B A", "Reversed stable sort";
690 @input = reverse sort @input;
691 is "@input", "I H G F E D C B A", "Reversed stable in place sort";
694 $output = reverse sort @input;
695 is $output, "IHGFEDCBA", "Reversed stable sort in scalar context";
698 @output = reverse sort {$a <=> $b} @input;
699 is "@output", "I H G F E D C B A", 'reversed stable $a <=> $b sort';
702 @input = reverse sort {$a <=> $b} @input;
703 is "@input", "I H G F E D C B A", 'revesed stable $a <=> $b in place sort';
706 $output = reverse sort {$a <=> $b} @input;
707 is $output, "IHGFEDCBA", 'reversed stable $a <=> $b sort in scalar context';
710 @output = reverse sort {$b <=> $a} @input;
711 is "@output", "C B A F E D I H G", 'reversed stable $b <=> $a sort';
714 @input = reverse sort {$b <=> $a} @input;
715 is "@input", "C B A F E D I H G", 'revesed stable $b <=> $a in place sort';
718 $output = reverse sort {$b <=> $a} @input;
719 is $output, "CBAFEDIHG", 'reversed stable $b <=> $a sort in scalar context';
722 @output = reverse sort {stuff || $a <=> $b} @input;
723 is "@output", "I H G F E D C B A", 'reversed stable complex sort';
726 @input = reverse sort {stuff || $a <=> $b} @input;
727 is "@input", "I H G F E D C B A", 'revesed stable complex in place sort';
730 $output = reverse sort {stuff || $a <=> $b} @input;
731 is $output, "IHGFEDCBA", 'reversed stable complex sort in scalar context';
734 reverse sort {$a <=> $b} @_;
737 @output = sortnumr &generate1;
738 is "@output", "I H G F E D C B A",
739 'reversed stable $a <=> $b sort return list context';
740 $output = sortnumr &generate1;
741 is $output, "IHGFEDCBA", 'reversed stable $a <=> $b sort return scalar context';
744 reverse sort {$b <=> $a} @_;
747 @output = sortnumrba &generate1;
748 is "@output", "C B A F E D I H G",
749 'reversed stable $b <=> $a sort return list context';
750 $output = sortnumrba &generate1;
751 is $output, "CBAFEDIHG", 'reversed stable $b <=> $a sort return scalar context';
754 reverse sort {stuff || $a <=> $b} @_;
757 @output = sortnumrq &generate1;
758 is "@output", "I H G F E D C B A",
759 'reversed stable complex sort return list context';
760 $output = sortnumrq &generate1;
761 is $output, "IHGFEDCBA", 'reversed stable complex sort return scalar context';
763 @output = reverse (sort(qw(C A B)), 0);
764 is "@output", "0 C B A", 'reversed sort with trailing argument';
766 @output = reverse (0, sort(qw(C A B)));
767 is "@output", "C B A 0", 'reversed sort with leading argument';
769 eval { @output = sort {goto sub {}} 1,2; };
770 $fail_msg = q(Can't goto subroutine outside a subroutine);
771 cmp_ok(substr($@,0,length($fail_msg)),'eq',$fail_msg,'goto subr outside subr');
775 sub goto_sub {goto sub{}}
776 eval { @output = sort goto_sub 1,2; };
777 $fail_msg = q(Can't goto subroutine from a sort sub);
778 cmp_ok(substr($@,0,length($fail_msg)),'eq',$fail_msg,'goto subr from a sort sub');
782 eval { @output = sort {goto label} 1,2; };
783 $fail_msg = q(Can't "goto" out of a pseudo block);
784 cmp_ok(substr($@,0,length($fail_msg)),'eq',$fail_msg,'goto out of a pseudo block 1');
788 sub goto_label {goto label}
789 label: eval { @output = sort goto_label 1,2; };
790 $fail_msg = q(Can't "goto" out of a pseudo block);
791 cmp_ok(substr($@,0,length($fail_msg)),'eq',$fail_msg,'goto out of a pseudo block 2');
795 sub self_immolate {undef &self_immolate; $a<=>$b}
796 eval { @output = sort self_immolate 1,2,3 };
797 $fail_msg = q(Can't undef active subroutine);
798 cmp_ok(substr($@,0,length($fail_msg)),'eq',$fail_msg,'undef active subr');
801 for(1,2) # We run this twice, to make sure sort does not lower the ref
802 { # count. See bug 71076.
807 if (!defined($n)) { # No arg means we're being called by sort()
810 if ($n<5) { rec($n+1); }
811 else { () = sort rec 1,2; }
813 $failed = 1 if !defined $n;
817 ok(!$failed, "sort from active sub");
820 # $a and $b are set in the package the sort() is called from,
821 # *not* the package the sort sub is in. This is longstanding
822 # de facto behaviour that shouldn't be broken.
824 () = sort OtherPack::foo 1,2,3,4;
830 $answer = "something was unexpectedly defined or undefined" if
831 defined($a) || defined($b) || !defined($main::a) || !defined($main::b);
832 $main::a <=> $main::b;
836 cmp_ok($answer,'eq','good','sort subr called from other package');
839 # Bug 36430 - sort called in package2 while a
840 # sort in package1 is active should set $package2::a/b.
843 my @list = sort { A::min(@$a) <=> A::min(@$b) }
844 [3, 1, 5], [2, 4], [0];
846 cmp_ok($answer,'eq','good','bug 36430');
851 $answer = '$a and/or $b are not defined ' if !defined($a) || !defined($b);
860 # I commented out this TODO test because messing with FREEd scalars on the
861 # stack can have all sorts of strange side-effects, not made safe by eval
865 # local $TODO = "sort should make sure elements are not freed in the sort block";
866 # eval { @nomodify_x=(1..8);
867 # our @copy = sort { undef @nomodify_x; 1 } (@nomodify_x, 3); };
872 # Sorting shouldn't increase the refcount of a sub
874 sub sportello {(1+$a) <=> (1+$b)}
875 my $refcnt = &Internals::SvREFCNT(\&sportello);
876 @output = sort sportello 3,7,9;
880 ::is($refcnt, &Internals::SvREFCNT(\&::sportello), "sort sub refcnt");
881 $fail_msg = q(Modification of a read-only value attempted);
882 # Sorting a read-only array in-place shouldn't be allowed
883 my @readonly = (1..10);
884 Internals::SvREADONLY(@readonly, 1);
885 eval { @readonly = sort @readonly; };
886 ::cmp_ok(substr($@,0,length($fail_msg)),'eq',$fail_msg,'in-place sort of read-only array');
891 # Using return() should be okay even in a deeper context
892 @b = sort {while (1) {return ($a <=> $b)} } 1..10;
893 is("@b", "1 2 3 4 5 6 7 8 9 10", "return within loop");
895 # Using return() should be okay even if there are other items
896 # on the stack at the time.
897 @b = sort {$_ = ($a<=>$b) + do{return $b<=> $a}} 1..10;
898 is("@b", "10 9 8 7 6 5 4 3 2 1", "return with SVs on stack");
900 # As above, but with a sort sub rather than a sort block.
901 sub ret_with_stacked { $_ = ($a<=>$b) + do {return $b <=> $a} }
902 @b = sort ret_with_stacked 1..10;
903 is("@b", "10 9 8 7 6 5 4 3 2 1", "return with SVs on stack");
905 # Comparison code should be able to give result in non-integer representation.
906 sub cmp_as_string($$) { $_[0] < $_[1] ? "-1" : $_[0] == $_[1] ? "0" : "+1" }
907 @b = sort { cmp_as_string($a, $b) } (1,5,4,7,3,2,3);
908 is("@b", "1 2 3 3 4 5 7", "comparison result as string");
909 @b = sort cmp_as_string (1,5,4,7,3,2,3);
910 is("@b", "1 2 3 3 4 5 7", "comparison result as string");
912 # RT #34604: sort didn't honour overloading if the overloaded elements
913 # were retrieved via tie
918 sub TIEHASH { bless {
919 p => bless({ val => 2 }),
920 q => bless({ val => 1 }),
923 sub FETCH { $_[0]{$_[1] } }
926 sub compare { $cc++; $_[0]{val} cmp $_[1]{val} }
928 sub str { $cs++; $_[0]{val} }
930 use overload 'cmp' => \&compare, '""' => \&str;
934 tie my %h, 'RT34604';
935 my @sorted = sort @h{qw(p q)};
936 is($cc, 1, 'overload compare called once');
937 is("@sorted","1 2", 'overload sort result');
938 is($cs, 2, 'overload string called twice');
941 fresh_perl_is('sub w ($$) {my ($l, $r) = @_; my $v = \@_; undef @_; $l <=> $r}; print join q{ }, sort w 3, 1, 2, 0',
943 {stderr => 1, switches => ['-w']},
946 fresh_perl_is('sub w ($$) {my ($l, $r) = @_; my $v = \@_; undef @_; @_ = 0..2; $l <=> $r}; print join q{ }, sort w 3, 1, 2, 0',
948 {stderr => 1, switches => ['-w']},
972 is($count, 0, 'None before we start');
973 my @a = map { Counter->new() } 0..1;
974 is($count, 2, '2 here');
976 my @b = sort sorter @a;
979 cmp_ok($b[0], '<', $b[1], 'sorted!');
981 is($count, 2, 'still the same 2 here');
985 is($count, 0, 'all gone');
988 # [perl #77930] The context stack may be reallocated during a sort, as a
989 # result of deeply-nested (or not-so-deeply-nested) calls
990 # from a custom sort subroutine.
994 local $count = $count+1;
995 ()->$sub if $count < 1000;
998 () = sort $sub qw<a b c d e f g>;
1003 '[perl #77930] cx_stack reallocation during sort'
1007 # Match vars should not leak from one sort sub call to the next
1012 "Leakage" =~ /(.*)/;
1017 "Leakage" =~ /(.*)/;
1022 my @b = sort soarter 0..2;
1024 like $output, qr/^(?:Win)+\z/,
1025 "Match vars do not leak from one plain sort sub to the next";
1030 @b = sort soarterdd 0..2;
1032 like $output, qr/^(?:Win)+\z/,
1033 'Match vars do not leak from one $$ sort sub to the next';
1036 # [perl #30661] autoloading
1037 AUTOLOAD { $b <=> $a }
1039 is join("", sort stubbedsub split//, '04381091'), '98431100',
1040 'stubborn AUTOLOAD';
1041 is join("", sort hopefullynonexistent split//, '04381091'), '98431100',
1042 'AUTOLOAD without stub';
1043 my $stubref = \&givemeastub;
1044 is join("", sort $stubref split//, '04381091'), '98431100',
1045 'AUTOLOAD with stubref';
1047 # [perl #90030] sort without arguments
1048 eval '@x = (sort); 1';
1049 is $@, '', '(sort) does not die';
1050 is @x, 0, '(sort) returns empty list';
1051 eval '@x = sort; 1';
1052 is $@, '', 'sort; does not die';
1053 is @x, 0, 'sort; returns empty list';
1054 eval '{@x = sort} 1';
1055 is $@, '', '{sort} does not die';
1056 is @x, 0, '{sort} returns empty list';
1058 # this happened while the padrange op was being added. Sort blocks
1059 # are executed in void context, and the padrange op was skipping pushing
1060 # the item in void cx. The net result was that the return value was
1061 # whatever was on the stack last.
1067 undef; # this got returned by mistake
1072 is "@a", "0 1 3 5 6", "padrange and void context";
1075 # Fatal warnings an sort sub returning a non-number
1076 # We need two evals, because the panic used to happen on scope exit.
1077 eval { eval { use warnings FATAL => 'all'; () = sort { undef } 1,2 } };
1079 'no panic/crash with fatal warnings when sort sub returns undef';
1080 eval { eval { use warnings FATAL => 'all'; () = sort { "no thin" } 1,2 } };
1082 'no panic/crash with fatal warnings when sort sub returns string';
1083 sub notdef($$) { undef }
1084 eval { eval { use warnings FATAL => 'all'; () = sort notdef 1,2 } };
1086 'no panic/crash with fatal warnings when sort sub($$) returns undef';
1087 sub yarn($$) { "no thinking aloud" }
1088 eval { eval { use warnings FATAL => 'all'; () = sort yarn 1,2 } };
1090 'no panic/crash with fatal warnings when sort sub($$) returns string';
1093 () = [sort { $a = 10; $b = 10; 0 } $#a, $#a];
1094 is $#a, 10, 'sort block modifying $a and $b';
1097 is \$a, \$a, '[perl #78194] op return values passed to sort'; 0
1098 } "${\''}", "${\''}";
1101 @_=sort { delete $deletions::{a}; delete $deletions::{b}; 3 } 1..3;
1103 pass "no crash when sort block deletes *a and *b";
1105 # make sure return args are always evaluated in scalar context
1111 sub f1 { $b <=> $a, $a <=> $b }
1112 sub f2 { return ($b <=> $a, $a <=> $b) }
1113 sub f3 { for ($b <=> $a) { return ($b <=> $a, $a <=> $b) } }
1116 no warnings 'uninitialized';
1117 ::is (join('-', sort { () } 3,1,2,4), '3-1-2-4', "Ret: null blk");
1119 ::is (join('-', sort { $b <=> $a, $a <=> $b } 3,1,2,4), '1-2-3-4', "Ret: blk");
1120 ::is (join('-', sort { for($b <=> $a) { return ($b <=> $a, $a <=> $b) } }
1121 3,1,2,4), '1-2-3-4', "Ret: blk ret");
1123 no warnings 'uninitialized';
1124 ::is (join('-', sort f0 3,1,2,4), '3-1-2-4', "Ret: f0");
1126 ::is (join('-', sort f1 3,1,2,4), '1-2-3-4', "Ret: f1");
1127 ::is (join('-', sort f2 3,1,2,4), '1-2-3-4', "Ret: f2");
1128 ::is (join('-', sort f3 3,1,2,4), '1-2-3-4', "Ret: f3");
1132 @a = sort{ *a=0; 1} 0..1;
1133 pass "No crash when GP deleted out from under us [perl 124097]";
1135 no warnings 'redefine';
1136 # some alternative non-solutions localized modifications to *a and *b
1138 @a = sort { *a = sub { 1 }; $a <=> $b } 0 .. 1;
1139 ok(a(), "*a wasn't localized inadvertantly");