This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
fix GvSV refcounting in sort
[perl5.git] / t / op / sort.t
CommitLineData
a687059c 1#!./perl
d0664088 2$|=1;
a687059c 3
9c007264
JH
4BEGIN {
5 chdir 't' if -d 't';
ab4454fc 6 require './test.pl';
43ece5b1 7 set_up_inc('../lib');
9c007264 8}
9f1b1f2d 9use warnings;
16ada235 10plan(tests => 200);
a687059c 11
71a29c3c
GS
12# these shouldn't hang
13{
14 no warnings;
15 sort { for ($_ = 0;; $_++) {} } @a;
16 sort { while(1) {} } @a;
17 sort { while(1) { last; } } @a;
18 sort { while(0) { last; } } @a;
1937c63e
ST
19
20 # Change 26011: Re: A surprising segfault
21 map scalar(sort(+())), ('')x68;
71a29c3c
GS
22}
23
9f1b1f2d
GS
24sub Backwards { $a lt $b ? 1 : $a gt $b ? -1 : 0 }
25sub Backwards_stacked($$) { my($a,$b) = @_; $a lt $b ? 1 : $a gt $b ? -1 : 0 }
9850bf21 26sub Backwards_other { $a lt $b ? 1 : $a gt $b ? -1 : 0 }
a687059c 27
9d116dd7
JH
28my $upperfirst = 'A' lt 'a';
29
30# Beware: in future this may become hairier because of possible
59608b94 31# collation complications: qw(A a B b) can be sorted at least as
9d116dd7
JH
32# any of the following
33#
34# A a B b
35# A B a b
36# a b A B
37# a A b B
38#
39# All the above orders make sense.
40#
41# That said, EBCDIC sorts all small letters first, as opposed
42# to ASCII which sorts all big letters first.
43
a687059c 44@harry = ('dog','cat','x','Cain','Abel');
2f52a358 45@george = ('gone','chased','yz','punished','Axed');
a687059c
LW
46
47$x = join('', sort @harry);
9d116dd7 48$expected = $upperfirst ? 'AbelCaincatdogx' : 'catdogxAbelCain';
f34362ee
DL
49
50cmp_ok($x,'eq',$expected,'upper first 1');
a687059c 51
9f1b1f2d 52$x = join('', sort( Backwards @harry));
9d116dd7 53$expected = $upperfirst ? 'xdogcatCainAbel' : 'CainAbelxdogcat';
f34362ee
DL
54
55cmp_ok($x,'eq',$expected,'upper first 2');
a687059c 56
9f1b1f2d 57$x = join('', sort( Backwards_stacked @harry));
43481408 58$expected = $upperfirst ? 'xdogcatCainAbel' : 'CainAbelxdogcat';
f34362ee
DL
59
60cmp_ok($x,'eq',$expected,'upper first 3');
43481408 61
a687059c 62$x = join('', sort @george, 'to', @harry);
9d116dd7
JH
63$expected = $upperfirst ?
64 'AbelAxedCaincatchaseddoggonepunishedtoxyz' :
65 'catchaseddoggonepunishedtoxyzAbelAxedCain' ;
03a14243 66
d0664088
KW
67my @initially_sorted = ( 0 .. 260,
68 0x3FF, 0x400, 0x401,
69 0x7FF, 0x800, 0x801,
70 0x3FFF, 0x4000, 0x4001,
71 0xFFFF, 0x10000, 0x10001,
72 );
73# It makes things easier below if there are an even number of elements in the
74# array.
75if (scalar(@initially_sorted) % 2 == 1) {
76 push @initially_sorted, $initially_sorted[-1] + 1;
77}
78
79# We convert to a chr(), but prepend a constant string to make sure things can
80# work on more than a single character.
81my $prefix = "a\xb6";
82my $prefix_len = length $prefix;
83
84my @chr_initially_sorted = @initially_sorted;
85$_ = $prefix . chr($_) for @chr_initially_sorted;
86
87# Create a very unsorted version by reversing it, and then pushing the same
88# code points again, but pair-wise reversed.
89my @initially_unsorted = reverse @chr_initially_sorted;
90for (my $i = 0; $i < @chr_initially_sorted - 1; $i += 2) {
91 push @initially_unsorted, $chr_initially_sorted[$i+1],
92 $chr_initially_sorted[$i];
93}
94
95# And, an all-UTF-8 version
96my @utf8_initialy_unsorted = @initially_unsorted;
97utf8::upgrade($_) for @utf8_initialy_unsorted;
98
99# Sort the non-UTF-8 version
100my @non_utf8_result = sort @initially_unsorted;
101my @wrongly_utf8;
102my $ordered_correctly = 1;
103for 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])
106 {
107 $ordered_correctly = 0;
108 last;
109 }
110 push @wrongly_utf8, $i if $i < 256 && utf8::is_utf8($non_utf8_result[$i]);
111}
112if (! 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);
115}
116if (! is(@wrongly_utf8, 0,
117 "No elements were wrongly converted to utf8 in sorting"))
118{
119 diag "For code points " . join " ", @wrongly_utf8;
120}
121
122# And then the UTF-8 one
123my @wrongly_non_utf8;
124$ordered_correctly = 1;
125my @utf8_result = sort @utf8_initialy_unsorted;
126for 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])
129 {
130 $ordered_correctly = 0;
131 last;
132 }
133 push @wrongly_non_utf8, $i unless utf8::is_utf8($utf8_result[$i]);
134}
135if (! 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);
138}
139if (! is(@wrongly_non_utf8, 0,
140 "No elements were wrongly converted from utf8 in sorting"))
141{
142 diag "For code points " . join " ", @wrongly_non_utf8;
143}
144
f34362ee
DL
145cmp_ok($x,'eq',$expected,'upper first 4');
146$" = ' ';
03a14243
LW
147@a = ();
148@b = reverse @a;
f34362ee 149cmp_ok("@b",'eq',"",'reverse 1');
03a14243
LW
150
151@a = (1);
152@b = reverse @a;
f34362ee 153cmp_ok("@b",'eq',"1",'reverse 2');
03a14243
LW
154
155@a = (1,2);
156@b = reverse @a;
f34362ee 157cmp_ok("@b",'eq',"2 1",'reverse 3');
03a14243
LW
158
159@a = (1,2,3);
160@b = reverse @a;
f34362ee 161cmp_ok("@b",'eq',"3 2 1",'reverse 4');
03a14243
LW
162
163@a = (1,2,3,4);
164@b = reverse @a;
f34362ee 165cmp_ok("@b",'eq',"4 3 2 1",'reverse 5');
55204971
LW
166
167@a = (10,2,3,4);
168@b = sort {$a <=> $b;} @a;
f34362ee 169cmp_ok("@b",'eq',"2 3 4 10",'sort numeric');
988174c1 170
9f1b1f2d 171$sub = 'Backwards';
988174c1 172$x = join('', sort $sub @harry);
9d116dd7 173$expected = $upperfirst ? 'xdogcatCainAbel' : 'CainAbelxdogcat';
f34362ee
DL
174
175cmp_ok($x,'eq',$expected,'sorter sub name in var 1');
43481408 176
9f1b1f2d 177$sub = 'Backwards_stacked';
43481408
GS
178$x = join('', sort $sub @harry);
179$expected = $upperfirst ? 'xdogcatCainAbel' : 'CainAbelxdogcat';
f34362ee
DL
180
181cmp_ok($x,'eq',$expected,'sorter sub name in var 2');
988174c1 182
cd5de442
GS
183# literals, combinations
184
185@b = sort (4,1,3,2);
f34362ee
DL
186cmp_ok("@b",'eq','1 2 3 4','just sort');
187
cd5de442
GS
188
189@b = sort grep { $_ } (4,1,3,2);
f34362ee
DL
190cmp_ok("@b",'eq','1 2 3 4','grep then sort');
191
cd5de442
GS
192
193@b = sort map { $_ } (4,1,3,2);
f34362ee
DL
194cmp_ok("@b",'eq','1 2 3 4','map then sort');
195
cd5de442
GS
196
197@b = sort reverse (4,1,3,2);
f34362ee
DL
198cmp_ok("@b",'eq','1 2 3 4','reverse then sort');
199
200
01b5ef50
FC
201@b = sort CORE::reverse (4,1,3,2);
202cmp_ok("@b",'eq','1 2 3 4','CORE::reverse then sort');
203
487e470d
FC
204eval { @b = sort CORE::revers (4,1,3,2); };
205like($@, qr/^Undefined sort subroutine "CORE::revers" called at /);
01b5ef50 206
7bac28a0 207
9850bf21 208sub twoface { no warnings 'redefine'; *twoface = sub { $a <=> $b }; &twoface }
7bac28a0 209eval { @b = sort twoface 4,1,3,2 };
f34362ee
DL
210cmp_ok("@b",'eq','1 2 3 4','redefine sort sub inside the sort sub');
211
7bac28a0 212
9f1b1f2d 213eval { no warnings 'redefine'; *twoface = sub { &Backwards } };
f34362ee 214ok(!$@,"redefining sort subs outside the sort \$@=[$@]");
7bac28a0
PP
215
216eval { @b = sort twoface 4,1,3,2 };
f34362ee 217cmp_ok("@b",'eq','4 3 2 1','twoface redefinition');
7bac28a0 218
9f1b1f2d
GS
219{
220 no warnings 'redefine';
9850bf21 221 *twoface = sub { *twoface = *Backwards_other; $a <=> $b };
9f1b1f2d 222}
f34362ee 223
9850bf21 224eval { @b = sort twoface 4,1,9,5 };
f34362ee 225ok(($@ eq "" && "@b" eq "1 4 5 9"),'redefinition should not take effect during the sort');
7bac28a0 226
9f1b1f2d
GS
227{
228 no warnings 'redefine';
229 *twoface = sub {
7bac28a0 230 eval 'sub twoface { $a <=> $b }';
f34362ee 231 die($@ eq "" ? "good\n" : "bad\n");
7bac28a0
PP
232 $a <=> $b;
233 };
9f1b1f2d 234}
7bac28a0 235eval { @b = sort twoface 4,1 };
f34362ee 236cmp_ok(substr($@,0,4), 'eq', 'good', 'twoface eval');
15f0808c
GS
237
238eval <<'CODE';
9f1b1f2d 239 my @result = sort main'Backwards 'one', 'two';
15f0808c 240CODE
f34362ee 241cmp_ok($@,'eq','',q(old skool package));
15f0808c
GS
242
243eval <<'CODE';
244 # "sort 'one', 'two'" should not try to parse "'one" as a sort sub
245 my @result = sort 'one', 'two';
246CODE
f34362ee 247cmp_ok($@,'eq','',q(one is not a sub));
c6e96bcb
GS
248
249{
9f1b1f2d
GS
250 my $sortsub = \&Backwards;
251 my $sortglob = *Backwards;
252 my $sortglobr = \*Backwards;
253 my $sortname = 'Backwards';
c6e96bcb 254 @b = sort $sortsub 4,1,3,2;
f34362ee 255 cmp_ok("@b",'eq','4 3 2 1','sortname 1');
c6e96bcb 256 @b = sort $sortglob 4,1,3,2;
f34362ee 257 cmp_ok("@b",'eq','4 3 2 1','sortname 2');
c6e96bcb 258 @b = sort $sortname 4,1,3,2;
f34362ee 259 cmp_ok("@b",'eq','4 3 2 1','sortname 3');
62f274bf 260 @b = sort $sortglobr 4,1,3,2;
f34362ee 261 cmp_ok("@b",'eq','4 3 2 1','sortname 4');
43481408
GS
262}
263
264{
9f1b1f2d
GS
265 my $sortsub = \&Backwards_stacked;
266 my $sortglob = *Backwards_stacked;
267 my $sortglobr = \*Backwards_stacked;
268 my $sortname = 'Backwards_stacked';
43481408 269 @b = sort $sortsub 4,1,3,2;
f34362ee 270 cmp_ok("@b",'eq','4 3 2 1','sortname 5');
43481408 271 @b = sort $sortglob 4,1,3,2;
f34362ee 272 cmp_ok("@b",'eq','4 3 2 1','sortname 6');
43481408 273 @b = sort $sortname 4,1,3,2;
f34362ee 274 cmp_ok("@b",'eq','4 3 2 1','sortname 7');
43481408 275 @b = sort $sortglobr 4,1,3,2;
f34362ee 276 cmp_ok("@b",'eq','4 3 2 1','sortname 8');
c6e96bcb
GS
277}
278
279{
9f1b1f2d
GS
280 local $sortsub = \&Backwards;
281 local $sortglob = *Backwards;
282 local $sortglobr = \*Backwards;
283 local $sortname = 'Backwards';
c6e96bcb 284 @b = sort $sortsub 4,1,3,2;
f34362ee 285 cmp_ok("@b",'eq','4 3 2 1','sortname local 1');
c6e96bcb 286 @b = sort $sortglob 4,1,3,2;
f34362ee 287 cmp_ok("@b",'eq','4 3 2 1','sortname local 2');
c6e96bcb 288 @b = sort $sortname 4,1,3,2;
f34362ee 289 cmp_ok("@b",'eq','4 3 2 1','sortname local 3');
62f274bf 290 @b = sort $sortglobr 4,1,3,2;
f34362ee 291 cmp_ok("@b",'eq','4 3 2 1','sortname local 4');
43481408
GS
292}
293
294{
9f1b1f2d
GS
295 local $sortsub = \&Backwards_stacked;
296 local $sortglob = *Backwards_stacked;
297 local $sortglobr = \*Backwards_stacked;
298 local $sortname = 'Backwards_stacked';
43481408 299 @b = sort $sortsub 4,1,3,2;
f34362ee 300 cmp_ok("@b",'eq','4 3 2 1','sortname local 5');
43481408 301 @b = sort $sortglob 4,1,3,2;
f34362ee 302 cmp_ok("@b",'eq','4 3 2 1','sortname local 6');
43481408 303 @b = sort $sortname 4,1,3,2;
f34362ee 304 cmp_ok("@b",'eq','4 3 2 1','sortname local 7');
43481408 305 @b = sort $sortglobr 4,1,3,2;
f34362ee 306 cmp_ok("@b",'eq','4 3 2 1','sortname local 8');
c6e96bcb
GS
307}
308
9c007264
JH
309## exercise sort builtins... ($a <=> $b already tested)
310@a = ( 5, 19, 1996, 255, 90 );
5d4fa709
GS
311@b = sort {
312 my $dummy; # force blockness
313 return $b <=> $a
314} @a;
f34362ee
DL
315cmp_ok("@b",'eq','1996 255 90 19 5','force blockness');
316
9c007264
JH
317$x = join('', sort { $a cmp $b } @harry);
318$expected = $upperfirst ? 'AbelCaincatdogx' : 'catdogxAbelCain';
f34362ee
DL
319cmp_ok($x,'eq',$expected,'a cmp b');
320
9c007264
JH
321$x = join('', sort { $b cmp $a } @harry);
322$expected = $upperfirst ? 'xdogcatCainAbel' : 'CainAbelxdogcat';
f34362ee
DL
323cmp_ok($x,'eq',$expected,'b cmp a');
324
9c007264
JH
325{
326 use integer;
327 @b = sort { $a <=> $b } @a;
f34362ee
DL
328 cmp_ok("@b",'eq','5 19 90 255 1996','integer a <=> b');
329
9c007264 330 @b = sort { $b <=> $a } @a;
f34362ee
DL
331 cmp_ok("@b",'eq','1996 255 90 19 5','integer b <=> a');
332
9c007264
JH
333 $x = join('', sort { $a cmp $b } @harry);
334 $expected = $upperfirst ? 'AbelCaincatdogx' : 'catdogxAbelCain';
f34362ee
DL
335 cmp_ok($x,'eq',$expected,'integer a cmp b');
336
9c007264
JH
337 $x = join('', sort { $b cmp $a } @harry);
338 $expected = $upperfirst ? 'xdogcatCainAbel' : 'CainAbelxdogcat';
f34362ee
DL
339 cmp_ok($x,'eq',$expected,'integer b cmp a');
340
9c007264 341}
e507f050 342
f34362ee
DL
343
344
e507f050 345$x = join('', sort { $a <=> $b } 3, 1, 2);
f34362ee 346cmp_ok($x,'eq','123',q(optimized-away comparison block doesn't take any other arguments away with it));
e507f050 347
9c007264 348# test sorting in non-main package
5823dc9f
MS
349{
350 package Foo;
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');
8e3f9bdf 354
5823dc9f
MS
355 @b = sort ::Backwards_stacked @a;
356 ::cmp_ok("@b",'eq','90 5 255 1996 19','not in main:: 2');
f34362ee 357
5823dc9f
MS
358 # check if context for sort arguments is handled right
359 sub test_if_list {
360 my $gimme = wantarray;
361 ::is($gimme,1,'wantarray 1');
362 }
363 my $m = sub { $a <=> $b };
364
365 sub cxt_one { sort $m test_if_list() }
366 cxt_one();
367 sub cxt_two { sort { $a <=> $b } test_if_list() }
368 cxt_two();
369 sub cxt_three { sort &test_if_list() }
370 cxt_three();
e9d9e6f3
FC
371 sub cxt_three_anna_half { sort 0, test_if_list() }
372 cxt_three_anna_half();
5823dc9f
MS
373
374 sub test_if_scalar {
375 my $gimme = wantarray;
376 ::is(!($gimme or !defined($gimme)),1,'wantarray 2');
377 }
f34362ee 378
5823dc9f
MS
379 $m = \&test_if_scalar;
380 sub cxt_four { sort $m 1,2 }
381 @x = cxt_four();
382 sub cxt_five { sort { test_if_scalar($a,$b); } 1,2 }
383 @x = cxt_five();
384 sub cxt_six { sort test_if_scalar 1,2 }
385 @x = cxt_six();
8e3f9bdf
GS
386}
387
8e664e10
GS
388
389# test against a reentrancy bug
390{
391 package Bar;
392 sub compare { $a cmp $b }
393 sub reenter { my @force = sort compare qw/a b/ }
394}
395{
396 my($def, $init) = (0, 0);
397 @b = sort {
398 $def = 1 if defined $Bar::a;
399 Bar::reenter() unless $init++;
400 $a <=> $b
401 } qw/4 3 1 2/;
5823dc9f 402 cmp_ok("@b",'eq','1 2 3 4','reenter 1');
f34362ee 403
5823dc9f 404 ok(!$def,'reenter 2');
8e664e10 405}
f0670693 406
f34362ee 407
f0670693
SC
408{
409 sub routine { "one", "two" };
410 @a = sort(routine(1));
ee95e30c 411 cmp_ok("@a",'eq',"one two",'bug id 19991001.003 (#1549)');
f0670693 412}
fe1bc4cf
DM
413
414
fe1bc4cf
DM
415# check for in-place optimisation of @a = sort @a
416{
417 my ($r1,$r2,@a);
418 our @g;
419 @g = (3,2,1); $r1 = \$g[2]; @g = sort @g; $r2 = \$g[0];
45c198c1 420 is "$$r1-$$r2-@g", "1-1-1 2 3", "inplace sort of global";
fe1bc4cf
DM
421
422 @a = qw(b a c); $r1 = \$a[1]; @a = sort @a; $r2 = \$a[0];
45c198c1 423 is "$$r1-$$r2-@a", "a-a-a b c", "inplace sort of lexical";
fe1bc4cf
DM
424
425 @g = (2,3,1); $r1 = \$g[1]; @g = sort { $b <=> $a } @g; $r2 = \$g[0];
45c198c1 426 is "$$r1-$$r2-@g", "3-3-3 2 1", "inplace reversed sort of global";
fe1bc4cf
DM
427
428 @g = (2,3,1);
429 $r1 = \$g[1]; @g = sort { $a<$b?1:$a>$b?-1:0 } @g; $r2 = \$g[0];
45c198c1 430 is "$$r1-$$r2-@g", "3-3-3 2 1", "inplace custom sort of global";
fe1bc4cf
DM
431
432 sub mysort { $b cmp $a };
433 @a = qw(b c a); $r1 = \$a[1]; @a = sort mysort @a; $r2 = \$a[0];
45c198c1 434 is "$$r1-$$r2-@a", "c-c-c b a", "inplace sort with function of lexical";
fe1bc4cf
DM
435
436 use Tie::Array;
db7511db
DM
437 my @t;
438 tie @t, 'Tie::StdArray';
fe1bc4cf 439
db7511db 440 @t = qw(b c a); @t = sort @t;
5823dc9f 441 is "@t", "a b c", "inplace sort of tied array";
fe1bc4cf 442
db7511db 443 @t = qw(b c a); @t = sort mysort @t;
5823dc9f 444 is "@t", "c b a", "inplace sort of tied array with function";
db7511db
DM
445
446 # [perl #29790] don't optimise @a = ('a', sort @a) !
447
448 @g = (3,2,1); @g = ('0', sort @g);
5823dc9f 449 is "@g", "0 1 2 3", "un-inplace sort of global";
db7511db 450 @g = (3,2,1); @g = (sort(@g),'4');
5823dc9f 451 is "@g", "1 2 3 4", "un-inplace sort of global 2";
db7511db
DM
452
453 @a = qw(b a c); @a = ('x', sort @a);
5823dc9f 454 is "@a", "x a b c", "un-inplace sort of lexical";
db7511db 455 @a = qw(b a c); @a = ((sort @a), 'x');
5823dc9f 456 is "@a", "a b c x", "un-inplace sort of lexical 2";
db7511db
DM
457
458 @g = (2,3,1); @g = ('0', sort { $b <=> $a } @g);
5823dc9f 459 is "@g", "0 3 2 1", "un-inplace reversed sort of global";
db7511db 460 @g = (2,3,1); @g = ((sort { $b <=> $a } @g),'4');
5823dc9f 461 is "@g", "3 2 1 4", "un-inplace reversed sort of global 2";
db7511db
DM
462
463 @g = (2,3,1); @g = ('0', sort { $a<$b?1:$a>$b?-1:0 } @g);
5823dc9f 464 is "@g", "0 3 2 1", "un-inplace custom sort of global";
db7511db 465 @g = (2,3,1); @g = ((sort { $a<$b?1:$a>$b?-1:0 } @g),'4');
5823dc9f 466 is "@g", "3 2 1 4", "un-inplace custom sort of global 2";
db7511db
DM
467
468 @a = qw(b c a); @a = ('x', sort mysort @a);
5823dc9f 469 is "@a", "x c b a", "un-inplace sort with function of lexical";
db7511db 470 @a = qw(b c a); @a = ((sort mysort @a),'x');
5823dc9f 471 is "@a", "c b a x", "un-inplace sort with function of lexical 2";
aa6341cb
GG
472
473 # RT#54758. Git 62b40d2474e7487e6909e1872b6bccdf812c6818
8c1a9f82 474 no warnings 'void';
aa6341cb 475 my @m; push @m, 0 for 1 .. 1024; $#m; @m = sort @m;
5823dc9f 476 ::pass("in-place sorting segfault");
84721d61
DM
477
478 # RT #39358 - array should be preserved during sort
479
480 {
481 my @aa = qw(b c a);
482 my @copy;
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";
486 }
45c198c1
DM
487
488 # RT #128340: in-place sort incorrectly preserves element lvalue identity
489
490 @a = (5, 4, 3);
491 my $r = \$a[2];
492 @a = sort { $a <=> $b } @a;
493 $$r = "z";
494 is ("@a", "3 4 5", "RT #128340");
f6107ca2 495}
45c198c1 496
f6107ca2
DIM
497# in-place sorting of weak references
498SKIP: {
499 skip_if_miniperl("no dynamic loading on miniperl, no extension Scalar::Util", 1);
500 require Scalar::Util;
501 my @a = map { \(my $dummy = $_) } qw(c a d b);
502 my $r = $a[1];
503 Scalar::Util::weaken($a[1]);
504 @a = sort { $$a cmp $$b } @a;
505 undef $r;
506 ok defined $a[0] && ${$a[0]} eq 'a', "in-place sort strengthens weak references";
fe1bc4cf
DM
507}
508
eb209983
NC
509# Test optimisations of reversed sorts. As we now guarantee stability by
510# default, # optimisations which do not provide this are bogus.
fe1bc4cf 511
eb209983
NC
512{
513 package Oscalar;
514 use overload (qw("" stringify 0+ numify fallback 1));
515
516 sub new {
517 bless [$_[1], $_[2]], $_[0];
518 }
519
520 sub stringify { $_[0]->[0] }
521
522 sub numify { $_[0]->[1] }
523}
524
525sub generate {
526 my $count = 0;
527 map {new Oscalar $_, $count++} qw(A A A B B B C C C);
528}
529
530my @input = &generate;
531my @output = sort @input;
5823dc9f 532is join(" ", map {0+$_} @output), "0 1 2 3 4 5 6 7 8", "Simple stable sort";
eb209983
NC
533
534@input = &generate;
535@input = sort @input;
5823dc9f 536is join(" ", map {0+$_} @input), "0 1 2 3 4 5 6 7 8",
eb209983
NC
537 "Simple stable in place sort";
538
539# This won't be very interesting
540@input = &generate;
541@output = sort {$a <=> $b} @input;
5823dc9f 542is "@output", "A A A B B B C C C", 'stable $a <=> $b sort';
eb209983
NC
543
544@input = &generate;
545@output = sort {$a cmp $b} @input;
5823dc9f 546is join(" ", map {0+$_} @output), "0 1 2 3 4 5 6 7 8", 'stable $a cmp $b sort';
eb209983
NC
547
548@input = &generate;
549@input = sort {$a cmp $b} @input;
5823dc9f 550is join(" ", map {0+$_} @input), "0 1 2 3 4 5 6 7 8",
eb209983
NC
551 'stable $a cmp $b in place sort';
552
553@input = &generate;
554@output = sort {$b cmp $a} @input;
5823dc9f 555is join(" ", map {0+$_} @output), "6 7 8 3 4 5 0 1 2", 'stable $b cmp $a sort';
eb209983
NC
556
557@input = &generate;
558@input = sort {$b cmp $a} @input;
5823dc9f 559is join(" ", map {0+$_} @input), "6 7 8 3 4 5 0 1 2",
eb209983
NC
560 'stable $b cmp $a in place sort';
561
75dd5fa4 562@input = &generate;
eb209983 563@output = reverse sort @input;
5823dc9f 564is join(" ", map {0+$_} @output), "8 7 6 5 4 3 2 1 0", "Reversed stable sort";
eb209983
NC
565
566@input = &generate;
567@input = reverse sort @input;
5823dc9f 568is join(" ", map {0+$_} @input), "8 7 6 5 4 3 2 1 0",
eb209983
NC
569 "Reversed stable in place sort";
570
75dd5fa4
NC
571@input = &generate;
572my $output = reverse sort @input;
5823dc9f 573is $output, "CCCBBBAAA", "Reversed stable sort in scalar context";
75dd5fa4 574
eb209983
NC
575
576@input = &generate;
577@output = reverse sort {$a cmp $b} @input;
5823dc9f 578is join(" ", map {0+$_} @output), "8 7 6 5 4 3 2 1 0",
eb209983
NC
579 'reversed stable $a cmp $b sort';
580
581@input = &generate;
582@input = reverse sort {$a cmp $b} @input;
5823dc9f 583is join(" ", map {0+$_} @input), "8 7 6 5 4 3 2 1 0",
eb209983
NC
584 'revesed stable $a cmp $b in place sort';
585
586@input = &generate;
7e7a548e 587$output = reverse sort {$a cmp $b} @input;
5823dc9f 588is $output, "CCCBBBAAA", 'Reversed stable $a cmp $b sort in scalar context';
75dd5fa4
NC
589
590@input = &generate;
eb209983 591@output = reverse sort {$b cmp $a} @input;
5823dc9f 592is join(" ", map {0+$_} @output), "2 1 0 5 4 3 8 7 6",
eb209983
NC
593 'reversed stable $b cmp $a sort';
594
595@input = &generate;
596@input = reverse sort {$b cmp $a} @input;
5823dc9f 597is join(" ", map {0+$_} @input), "2 1 0 5 4 3 8 7 6",
eb209983
NC
598 'revesed stable $b cmp $a in place sort';
599
75dd5fa4
NC
600@input = &generate;
601$output = reverse sort {$b cmp $a} @input;
5823dc9f 602is $output, "AAABBBCCC", 'Reversed stable $b cmp $a sort in scalar context';
75dd5fa4 603
7e7a548e
NC
604sub stuff {
605 # Something complex enough to defeat any constant folding optimiser
606 $$ - $$;
607}
608
609@input = &generate;
610@output = reverse sort {stuff || $a cmp $b} @input;
5823dc9f 611is join(" ", map {0+$_} @output), "8 7 6 5 4 3 2 1 0",
7e7a548e
NC
612 'reversed stable complex sort';
613
614@input = &generate;
615@input = reverse sort {stuff || $a cmp $b} @input;
5823dc9f 616is join(" ", map {0+$_} @input), "8 7 6 5 4 3 2 1 0",
7e7a548e
NC
617 'revesed stable complex in place sort';
618
619@input = &generate;
620$output = reverse sort {stuff || $a cmp $b } @input;
5823dc9f 621is $output, "CCCBBBAAA", 'Reversed stable complex sort in scalar context';
7e7a548e 622
a1824f2a
NC
623sub sortr {
624 reverse sort @_;
625}
626
627@output = sortr &generate;
5823dc9f 628is join(" ", map {0+$_} @output), "8 7 6 5 4 3 2 1 0",
a1824f2a
NC
629 'reversed stable sort return list context';
630$output = sortr &generate;
5823dc9f 631is $output, "CCCBBBAAA",
a1824f2a
NC
632 'reversed stable sort return scalar context';
633
634sub sortcmpr {
635 reverse sort {$a cmp $b} @_;
636}
637
638@output = sortcmpr &generate;
5823dc9f 639is join(" ", map {0+$_} @output), "8 7 6 5 4 3 2 1 0",
a1824f2a
NC
640 'reversed stable $a cmp $b sort return list context';
641$output = sortcmpr &generate;
5823dc9f 642is $output, "CCCBBBAAA",
a1824f2a
NC
643 'reversed stable $a cmp $b sort return scalar context';
644
645sub sortcmprba {
646 reverse sort {$b cmp $a} @_;
647}
648
649@output = sortcmprba &generate;
5823dc9f 650is join(" ", map {0+$_} @output), "2 1 0 5 4 3 8 7 6",
a1824f2a
NC
651 'reversed stable $b cmp $a sort return list context';
652$output = sortcmprba &generate;
5823dc9f 653is $output, "AAABBBCCC",
a1824f2a 654'reversed stable $b cmp $a sort return scalar context';
eb209983 655
7e7a548e
NC
656sub sortcmprq {
657 reverse sort {stuff || $a cmp $b} @_;
658}
659
660@output = sortcmpr &generate;
5823dc9f 661is join(" ", map {0+$_} @output), "8 7 6 5 4 3 2 1 0",
7e7a548e
NC
662 'reversed stable complex sort return list context';
663$output = sortcmpr &generate;
5823dc9f 664is $output, "CCCBBBAAA",
7e7a548e
NC
665 'reversed stable complex sort return scalar context';
666
eb209983
NC
667# And now with numbers
668
669sub generate1 {
670 my $count = 'A';
671 map {new Oscalar $count++, $_} 0, 0, 0, 1, 1, 1, 2, 2, 2;
672}
673
674# This won't be very interesting
675@input = &generate1;
676@output = sort {$a cmp $b} @input;
5823dc9f 677is "@output", "A B C D E F G H I", 'stable $a cmp $b sort';
eb209983
NC
678
679@input = &generate1;
680@output = sort {$a <=> $b} @input;
5823dc9f 681is "@output", "A B C D E F G H I", 'stable $a <=> $b sort';
eb209983
NC
682
683@input = &generate1;
684@input = sort {$a <=> $b} @input;
5823dc9f 685is "@input", "A B C D E F G H I", 'stable $a <=> $b in place sort';
eb209983
NC
686
687@input = &generate1;
688@output = sort {$b <=> $a} @input;
5823dc9f 689is "@output", "G H I D E F A B C", 'stable $b <=> $a sort';
eb209983
NC
690
691@input = &generate1;
692@input = sort {$b <=> $a} @input;
5823dc9f 693is "@input", "G H I D E F A B C", 'stable $b <=> $a in place sort';
eb209983 694
59608b94
DN
695# test that optimized {$b cmp $a} and {$b <=> $a} remain stable
696# (new in 5.9) without overloading
697{ no warnings;
698@b = sort { $b <=> $a } @input = qw/5first 6first 5second 6second/;
5823dc9f 699is "@b" , "6first 6second 5first 5second", "optimized {$b <=> $a} without overloading" ;
59608b94 700@input = sort {$b <=> $a} @input;
5823dc9f 701is "@input" , "6first 6second 5first 5second","inline optimized {$b <=> $a} without overloading" ;
59608b94
DN
702};
703
eb209983 704# These two are actually doing string cmp on 0 1 and 2
75dd5fa4 705@input = &generate1;
eb209983 706@output = reverse sort @input;
5823dc9f 707is "@output", "I H G F E D C B A", "Reversed stable sort";
eb209983
NC
708
709@input = &generate1;
710@input = reverse sort @input;
5823dc9f 711is "@input", "I H G F E D C B A", "Reversed stable in place sort";
eb209983
NC
712
713@input = &generate1;
75dd5fa4 714$output = reverse sort @input;
5823dc9f 715is $output, "IHGFEDCBA", "Reversed stable sort in scalar context";
75dd5fa4
NC
716
717@input = &generate1;
eb209983 718@output = reverse sort {$a <=> $b} @input;
5823dc9f 719is "@output", "I H G F E D C B A", 'reversed stable $a <=> $b sort';
eb209983
NC
720
721@input = &generate1;
722@input = reverse sort {$a <=> $b} @input;
5823dc9f 723is "@input", "I H G F E D C B A", 'revesed stable $a <=> $b in place sort';
fe1bc4cf 724
eb209983 725@input = &generate1;
75dd5fa4 726$output = reverse sort {$a <=> $b} @input;
5823dc9f 727is $output, "IHGFEDCBA", 'reversed stable $a <=> $b sort in scalar context';
75dd5fa4
NC
728
729@input = &generate1;
eb209983 730@output = reverse sort {$b <=> $a} @input;
5823dc9f 731is "@output", "C B A F E D I H G", 'reversed stable $b <=> $a sort';
fe1bc4cf 732
eb209983
NC
733@input = &generate1;
734@input = reverse sort {$b <=> $a} @input;
5823dc9f 735is "@input", "C B A F E D I H G", 'revesed stable $b <=> $a in place sort';
75dd5fa4
NC
736
737@input = &generate1;
738$output = reverse sort {$b <=> $a} @input;
5823dc9f 739is $output, "CBAFEDIHG", 'reversed stable $b <=> $a sort in scalar context';
a1824f2a 740
7e7a548e
NC
741@input = &generate1;
742@output = reverse sort {stuff || $a <=> $b} @input;
5823dc9f 743is "@output", "I H G F E D C B A", 'reversed stable complex sort';
7e7a548e
NC
744
745@input = &generate1;
746@input = reverse sort {stuff || $a <=> $b} @input;
5823dc9f 747is "@input", "I H G F E D C B A", 'revesed stable complex in place sort';
7e7a548e
NC
748
749@input = &generate1;
750$output = reverse sort {stuff || $a <=> $b} @input;
5823dc9f 751is $output, "IHGFEDCBA", 'reversed stable complex sort in scalar context';
a1824f2a
NC
752
753sub sortnumr {
754 reverse sort {$a <=> $b} @_;
755}
756
757@output = sortnumr &generate1;
5823dc9f 758is "@output", "I H G F E D C B A",
a1824f2a
NC
759 'reversed stable $a <=> $b sort return list context';
760$output = sortnumr &generate1;
5823dc9f 761is $output, "IHGFEDCBA", 'reversed stable $a <=> $b sort return scalar context';
a1824f2a
NC
762
763sub sortnumrba {
764 reverse sort {$b <=> $a} @_;
765}
766
767@output = sortnumrba &generate1;
5823dc9f 768is "@output", "C B A F E D I H G",
a1824f2a
NC
769 'reversed stable $b <=> $a sort return list context';
770$output = sortnumrba &generate1;
5823dc9f 771is $output, "CBAFEDIHG", 'reversed stable $b <=> $a sort return scalar context';
7e7a548e
NC
772
773sub sortnumrq {
774 reverse sort {stuff || $a <=> $b} @_;
775}
776
777@output = sortnumrq &generate1;
5823dc9f 778is "@output", "I H G F E D C B A",
7e7a548e
NC
779 'reversed stable complex sort return list context';
780$output = sortnumrq &generate1;
5823dc9f 781is $output, "IHGFEDCBA", 'reversed stable complex sort return scalar context';
c093edd0
NC
782
783@output = reverse (sort(qw(C A B)), 0);
5823dc9f 784is "@output", "0 C B A", 'reversed sort with trailing argument';
c093edd0
NC
785
786@output = reverse (0, sort(qw(C A B)));
5823dc9f 787is "@output", "C B A 0", 'reversed sort with leading argument';
9850bf21
RH
788
789eval { @output = sort {goto sub {}} 1,2; };
f34362ee 790$fail_msg = q(Can't goto subroutine outside a subroutine);
5823dc9f 791cmp_ok(substr($@,0,length($fail_msg)),'eq',$fail_msg,'goto subr outside subr');
f34362ee
DL
792
793
9850bf21
RH
794
795sub goto_sub {goto sub{}}
796eval { @output = sort goto_sub 1,2; };
f34362ee 797$fail_msg = q(Can't goto subroutine from a sort sub);
5823dc9f 798cmp_ok(substr($@,0,length($fail_msg)),'eq',$fail_msg,'goto subr from a sort sub');
f34362ee
DL
799
800
9850bf21
RH
801
802eval { @output = sort {goto label} 1,2; };
f34362ee 803$fail_msg = q(Can't "goto" out of a pseudo block);
5823dc9f 804cmp_ok(substr($@,0,length($fail_msg)),'eq',$fail_msg,'goto out of a pseudo block 1');
f34362ee
DL
805
806
9850bf21
RH
807
808sub goto_label {goto label}
809label: eval { @output = sort goto_label 1,2; };
f34362ee 810$fail_msg = q(Can't "goto" out of a pseudo block);
5823dc9f 811cmp_ok(substr($@,0,length($fail_msg)),'eq',$fail_msg,'goto out of a pseudo block 2');
f34362ee
DL
812
813
9850bf21
RH
814
815sub self_immolate {undef &self_immolate; $a<=>$b}
816eval { @output = sort self_immolate 1,2,3 };
f34362ee 817$fail_msg = q(Can't undef active subroutine);
5823dc9f 818cmp_ok(substr($@,0,length($fail_msg)),'eq',$fail_msg,'undef active subr');
f34362ee
DL
819
820
8a27a13e
FC
821for(1,2) # We run this twice, to make sure sort does not lower the ref
822{ # count. See bug 71076.
9850bf21
RH
823 my $failed = 0;
824
825 sub rec {
826 my $n = shift;
827 if (!defined($n)) { # No arg means we're being called by sort()
828 return 1;
829 }
830 if ($n<5) { rec($n+1); }
831 else { () = sort rec 1,2; }
832
833 $failed = 1 if !defined $n;
834 }
835
836 rec(1);
5823dc9f 837 ok(!$failed, "sort from active sub");
9850bf21
RH
838}
839
840# $a and $b are set in the package the sort() is called from,
841# *not* the package the sort sub is in. This is longstanding
842# de facto behaviour that shouldn't be broken.
f34362ee 843my $answer = "good";
9850bf21
RH
844() = sort OtherPack::foo 1,2,3,4;
845
9da9462b
RGS
846{
847 package OtherPack;
848 no warnings 'once';
849 sub foo {
f34362ee 850 $answer = "something was unexpectedly defined or undefined" if
9da9462b
RGS
851 defined($a) || defined($b) || !defined($main::a) || !defined($main::b);
852 $main::a <=> $main::b;
853 }
854}
9850bf21 855
5823dc9f 856cmp_ok($answer,'eq','good','sort subr called from other package');
9850bf21
RH
857
858
859# Bug 36430 - sort called in package2 while a
860# sort in package1 is active should set $package2::a/b.
5823dc9f
MS
861{
862 my $answer = "good";
863 my @list = sort { A::min(@$a) <=> A::min(@$b) }
864 [3, 1, 5], [2, 4], [0];
865
866 cmp_ok($answer,'eq','good','bug 36430');
867
868 package A;
869 sub min {
870 my @list = sort {
871 $answer = '$a and/or $b are not defined ' if !defined($a) || !defined($b);
872 $a <=> $b;
873 } @_;
874 $list[0];
875 }
9850bf21
RH
876}
877
5823dc9f 878
f34362ee 879
a5f48505
DM
880# I commented out this TODO test because messing with FREEd scalars on the
881# stack can have all sorts of strange side-effects, not made safe by eval
882# - DAPM.
883#
884#{
885# local $TODO = "sort should make sure elements are not freed in the sort block";
886# eval { @nomodify_x=(1..8);
887# our @copy = sort { undef @nomodify_x; 1 } (@nomodify_x, 3); };
888# is($@, "");
889#}
84df657f 890
9850bf21
RH
891
892# Sorting shouldn't increase the refcount of a sub
5823dc9f 893{
7f4622ec
RGS
894 sub sportello {(1+$a) <=> (1+$b)}
895 my $refcnt = &Internals::SvREFCNT(\&sportello);
896 @output = sort sportello 3,7,9;
5823dc9f
MS
897
898 {
7f4622ec
RGS
899 package Doc;
900 ::is($refcnt, &Internals::SvREFCNT(\&::sportello), "sort sub refcnt");
5823dc9f
MS
901 $fail_msg = q(Modification of a read-only value attempted);
902 # Sorting a read-only array in-place shouldn't be allowed
903 my @readonly = (1..10);
904 Internals::SvREADONLY(@readonly, 1);
905 eval { @readonly = sort @readonly; };
906 ::cmp_ok(substr($@,0,length($fail_msg)),'eq',$fail_msg,'in-place sort of read-only array');
907 }
908}
f34362ee 909
9850bf21
RH
910
911# Using return() should be okay even in a deeper context
912@b = sort {while (1) {return ($a <=> $b)} } 1..10;
5823dc9f 913is("@b", "1 2 3 4 5 6 7 8 9 10", "return within loop");
d7507f74
RH
914
915# Using return() should be okay even if there are other items
916# on the stack at the time.
917@b = sort {$_ = ($a<=>$b) + do{return $b<=> $a}} 1..10;
5823dc9f 918is("@b", "10 9 8 7 6 5 4 3 2 1", "return with SVs on stack");
d7507f74
RH
919
920# As above, but with a sort sub rather than a sort block.
921sub ret_with_stacked { $_ = ($a<=>$b) + do {return $b <=> $a} }
922@b = sort ret_with_stacked 1..10;
5823dc9f 923is("@b", "10 9 8 7 6 5 4 3 2 1", "return with SVs on stack");
93e19c0f
Z
924
925# Comparison code should be able to give result in non-integer representation.
926sub cmp_as_string($$) { $_[0] < $_[1] ? "-1" : $_[0] == $_[1] ? "0" : "+1" }
927@b = sort { cmp_as_string($a, $b) } (1,5,4,7,3,2,3);
928is("@b", "1 2 3 3 4 5 7", "comparison result as string");
929@b = sort cmp_as_string (1,5,4,7,3,2,3);
930is("@b", "1 2 3 3 4 5 7", "comparison result as string");
bdbefedf
DM
931
932# RT #34604: sort didn't honour overloading if the overloaded elements
933# were retrieved via tie
934
935{
936 package RT34604;
937
938 sub TIEHASH { bless {
939 p => bless({ val => 2 }),
940 q => bless({ val => 1 }),
941 }
942 }
943 sub FETCH { $_[0]{$_[1] } }
944
945 my $cc = 0;
946 sub compare { $cc++; $_[0]{val} cmp $_[1]{val} }
947 my $cs = 0;
948 sub str { $cs++; $_[0]{val} }
949
950 use overload 'cmp' => \&compare, '""' => \&str;
951
952 package main;
953
954 tie my %h, 'RT34604';
955 my @sorted = sort @h{qw(p q)};
956 is($cc, 1, 'overload compare called once');
957 is("@sorted","1 2", 'overload sort result');
958 is($cs, 2, 'overload string called twice');
959}
8f443ca6 960
f3106bc8 961fresh_perl_is('sub w ($$) {my ($l, $r) = @_; my $v = \@_; undef @_; $l <=> $r}; print join q{ }, sort w 3, 1, 2, 0',
8f443ca6
GG
962 '0 1 2 3',
963 {stderr => 1, switches => ['-w']},
964 'RT #72334');
965
f3106bc8 966fresh_perl_is('sub w ($$) {my ($l, $r) = @_; my $v = \@_; undef @_; @_ = 0..2; $l <=> $r}; print join q{ }, sort w 3, 1, 2, 0',
8f443ca6
GG
967 '0 1 2 3',
968 {stderr => 1, switches => ['-w']},
969 'RT #72334');
133acf7b
NC
970
971{
972 my $count = 0;
973 {
974 package Counter;
975
976 sub new {
977 ++$count;
978 bless [];
979 }
980
981 sub DESTROY {
982 --$count;
983 }
984 }
985
986 sub sorter ($$) {
987 my ($l, $r) = @_;
988 my $q = \@_;
989 $l <=> $r;
990 }
991
992 is($count, 0, 'None before we start');
993 my @a = map { Counter->new() } 0..1;
994 is($count, 2, '2 here');
995
996 my @b = sort sorter @a;
997
998 is(scalar @b, 2);
999 cmp_ok($b[0], '<', $b[1], 'sorted!');
1000
1001 is($count, 2, 'still the same 2 here');
1002
1003 @a = (); @b = ();
1004
1005 is($count, 0, 'all gone');
1006}
8e7d0c4b
FC
1007
1008# [perl #77930] The context stack may be reallocated during a sort, as a
1009# result of deeply-nested (or not-so-deeply-nested) calls
1010# from a custom sort subroutine.
1011fresh_perl_is
1012 '
1013 $sub = sub {
1014 local $count = $count+1;
1015 ()->$sub if $count < 1000;
1016 $a cmp $b
1017 };
1018 () = sort $sub qw<a b c d e f g>;
1019 print "ok"
1020 ',
1021 'ok',
1022 {},
92c404cd 1023 '[perl #77930] cx_stack reallocation during sort'
8e7d0c4b 1024;
ad021bfb
FC
1025
1026# [perl #76026]
1027# Match vars should not leak from one sort sub call to the next
1028{
1029 my $output = '';
1030 sub soarter {
1031 $output .= $1;
1032 "Leakage" =~ /(.*)/;
1033 1
1034 }
1035 sub soarterdd($$) {
1036 $output .= $1;
1037 "Leakage" =~ /(.*)/;
1038 1
1039 }
1040
1041 "Win" =~ /(.*)/;
1042 my @b = sort soarter 0..2;
1043
1044 like $output, qr/^(?:Win)+\z/,
1045 "Match vars do not leak from one plain sort sub to the next";
1046
1047 $output = '';
1048
1049 "Win" =~ /(.*)/;
1050 @b = sort soarterdd 0..2;
1051
1052 like $output, qr/^(?:Win)+\z/,
1053 'Match vars do not leak from one $$ sort sub to the next';
1054}
f7bc00ea
FC
1055
1056# [perl #30661] autoloading
1057AUTOLOAD { $b <=> $a }
1058sub stubbedsub;
1059is join("", sort stubbedsub split//, '04381091'), '98431100',
1060 'stubborn AUTOLOAD';
1061is join("", sort hopefullynonexistent split//, '04381091'), '98431100',
1062 'AUTOLOAD without stub';
1063my $stubref = \&givemeastub;
1064is join("", sort $stubref split//, '04381091'), '98431100',
1065 'AUTOLOAD with stubref';
a46b39a8
FC
1066
1067# [perl #90030] sort without arguments
5d4b936e 1068eval '@x = (sort); 1';
a46b39a8
FC
1069is $@, '', '(sort) does not die';
1070is @x, 0, '(sort) returns empty list';
5d4b936e 1071eval '@x = sort; 1';
a46b39a8
FC
1072is $@, '', 'sort; does not die';
1073is @x, 0, 'sort; returns empty list';
1074eval '{@x = sort} 1';
1075is $@, '', '{sort} does not die';
1076is @x, 0, '{sort} returns empty list';
a7fd8ef6
DM
1077
1078# this happened while the padrange op was being added. Sort blocks
1079# are executed in void context, and the padrange op was skipping pushing
1080# the item in void cx. The net result was that the return value was
1081# whatever was on the stack last.
1082
1083{
1084 my @a = sort {
1085 my $r = $a <=> $b;
1086 if ($r) {
1087 undef; # this got returned by mistake
1088 return $r
1089 }
1090 return 0;
1091 } 5,1,3,6,0;
1092 is "@a", "0 1 3 5 6", "padrange and void context";
1093}
2f43ddf1
FC
1094
1095# Fatal warnings an sort sub returning a non-number
1096# We need two evals, because the panic used to happen on scope exit.
1097eval { eval { use warnings FATAL => 'all'; () = sort { undef } 1,2 } };
1098is $@, "",
1099 'no panic/crash with fatal warnings when sort sub returns undef';
1100eval { eval { use warnings FATAL => 'all'; () = sort { "no thin" } 1,2 } };
1101is $@, "",
1102 'no panic/crash with fatal warnings when sort sub returns string';
1103sub notdef($$) { undef }
1104eval { eval { use warnings FATAL => 'all'; () = sort notdef 1,2 } };
1105is $@, "",
1106 'no panic/crash with fatal warnings when sort sub($$) returns undef';
1107sub yarn($$) { "no thinking aloud" }
1108eval { eval { use warnings FATAL => 'all'; () = sort yarn 1,2 } };
1109is $@, "",
1110 'no panic/crash with fatal warnings when sort sub($$) returns string';
f65493df
FC
1111
1112$#a = -1;
1113() = [sort { $a = 10; $b = 10; 0 } $#a, $#a];
1114is $#a, 10, 'sort block modifying $a and $b';
2d885586 1115
2d885586
FC
1116() = sort {
1117 is \$a, \$a, '[perl #78194] op return values passed to sort'; 0
1118} "${\''}", "${\''}";
8465ba45
FC
1119
1120package deletions {
1121 @_=sort { delete $deletions::{a}; delete $deletions::{b}; 3 } 1..3;
1122}
1123pass "no crash when sort block deletes *a and *b";
33411212
DM
1124
1125# make sure return args are always evaluated in scalar context
1126
1127{
1128 package Ret;
1129 no warnings 'void';
1130 sub f0 { }
1131 sub f1 { $b <=> $a, $a <=> $b }
1132 sub f2 { return ($b <=> $a, $a <=> $b) }
1133 sub f3 { for ($b <=> $a) { return ($b <=> $a, $a <=> $b) } }
1134
1135 {
1136 no warnings 'uninitialized';
1137 ::is (join('-', sort { () } 3,1,2,4), '3-1-2-4', "Ret: null blk");
1138 }
1139 ::is (join('-', sort { $b <=> $a, $a <=> $b } 3,1,2,4), '1-2-3-4', "Ret: blk");
1140 ::is (join('-', sort { for($b <=> $a) { return ($b <=> $a, $a <=> $b) } }
1141 3,1,2,4), '1-2-3-4', "Ret: blk ret");
1142 {
1143 no warnings 'uninitialized';
1144 ::is (join('-', sort f0 3,1,2,4), '3-1-2-4', "Ret: f0");
1145 }
1146 ::is (join('-', sort f1 3,1,2,4), '1-2-3-4', "Ret: f1");
1147 ::is (join('-', sort f2 3,1,2,4), '1-2-3-4', "Ret: f2");
1148 ::is (join('-', sort f3 3,1,2,4), '1-2-3-4', "Ret: f3");
1149}
dc9ef998
TC
1150
1151{
1152 @a = sort{ *a=0; 1} 0..1;
1153 pass "No crash when GP deleted out from under us [perl 124097]";
1154
1155 no warnings 'redefine';
1156 # some alternative non-solutions localized modifications to *a and *b
1157 sub a { 0 };
1158 @a = sort { *a = sub { 1 }; $a <=> $b } 0 .. 1;
1159 ok(a(), "*a wasn't localized inadvertantly");
1160}
427fbfe8
TC
1161
1162SKIP:
1163{
1164 eval { require Config; 1 }
1165 or skip "Cannot load Config", 1;
1166 $Config::Config{ivsize} == 8
1167 or skip "this test can only fail with 64-bit integers", 1;
1168 # sort's built-in numeric comparison wasn't careful enough in a world
1169 # of integers with more significant digits than NVs
1170 my @in = ( "0", "20000000000000001", "20000000000000000" );
1171 my @out = sort { $a <=> $b } @in;
1172 is($out[1], "20000000000000000", "check sort order");
1173}
16ada235
Z
1174
1175# [perl #92264] refcounting of GvSV slot of *a and *b
1176{
1177 my $act;
1178 package ReportDestruction {
1179 sub new { bless({ p => $_[1] }, $_[0]) }
1180 sub DESTROY { $act .= $_[0]->{p}; }
1181 }
1182 $act = "";
1183 my $filla = \(ReportDestruction->new("[filla]"));
1184 () = sort { my $r = $a cmp $b; $act .= "0"; *a = \$$filla; $act .= "1"; $r }
1185 ReportDestruction->new("[sorta]"), "foo";
1186 $act .= "2";
1187 $filla = undef;
1188 is $act, "01[sorta]2[filla]";
1189 $act = "";
1190 my $fillb = \(ReportDestruction->new("[fillb]"));
1191 () = sort { my $r = $a cmp $b; $act .= "0"; *b = \$$fillb; $act .= "1"; $r }
1192 "foo", ReportDestruction->new("[sortb]");
1193 $act .= "2";
1194 $fillb = undef;
1195 is $act, "01[sortb]2[fillb]";
1196}