xref: /openbsd-src/gnu/usr.bin/perl/lib/overload.t (revision 50b7afb2c2c0993b0894d4e34bf857cb13ed9c80)
1#!./perl -T
2
3BEGIN {
4    chdir 't' if -d 't';
5    @INC = '../lib';
6    require Config;
7    if (($Config::Config{'extensions'} !~ m!\bList/Util\b!) ){
8	print "1..0 # Skip -- Perl configured without List::Util module\n";
9	exit 0;
10    }
11}
12
13package Oscalar;
14use overload (
15				# Anonymous subroutines:
16'+'	=>	sub {new Oscalar $ {$_[0]}+$_[1]},
17'-'	=>	sub {new Oscalar
18		       $_[2]? $_[1]-${$_[0]} : ${$_[0]}-$_[1]},
19'<=>'	=>	sub {new Oscalar
20		       $_[2]? $_[1]-${$_[0]} : ${$_[0]}-$_[1]},
21'cmp'	=>	sub {new Oscalar
22		       $_[2]? ($_[1] cmp ${$_[0]}) : (${$_[0]} cmp $_[1])},
23'*'	=>	sub {new Oscalar ${$_[0]}*$_[1]},
24'/'	=>	sub {new Oscalar
25		       $_[2]? $_[1]/${$_[0]} :
26			 ${$_[0]}/$_[1]},
27'%'	=>	sub {new Oscalar
28		       $_[2]? $_[1]%${$_[0]} : ${$_[0]}%$_[1]},
29'**'	=>	sub {new Oscalar
30		       $_[2]? $_[1]**${$_[0]} : ${$_[0]}-$_[1]},
31
32qw(
33""	stringify
340+	numify)			# Order of arguments insignificant
35);
36
37sub new {
38  my $foo = $_[1];
39  bless \$foo, $_[0];
40}
41
42sub stringify { "${$_[0]}" }
43sub numify { 0 + "${$_[0]}" }	# Not needed, additional overhead
44				# comparing to direct compilation based on
45				# stringify
46
47package main;
48
49$| = 1;
50BEGIN { require './test.pl' }
51plan tests => 5191;
52
53use Scalar::Util qw(tainted);
54
55$a = new Oscalar "087";
56$b= "$a";
57
58is($b, $a);
59is($b, "087");
60is(ref $a, "Oscalar");
61is($a, $a);
62is($a, "087");
63
64$c = $a + 7;
65
66is(ref $c, "Oscalar");
67isnt($c, $a);
68is($c, "94");
69
70$b=$a;
71
72is(ref $a, "Oscalar");
73
74$b++;
75
76is(ref $b, "Oscalar");
77is($a, "087");
78is($b, "88");
79is(ref $a, "Oscalar");
80
81$c=$b;
82$c-=$a;
83
84is(ref $c, "Oscalar");
85is($a, "087");
86is($c, "1");
87is(ref $a, "Oscalar");
88
89$b=1;
90$b+=$a;
91
92is(ref $b, "Oscalar");
93is($a, "087");
94is($b, "88");
95is(ref $a, "Oscalar");
96
97eval q[ package Oscalar; use overload ('++' => sub { $ {$_[0]}++;$_[0] } ) ];
98
99$b=$a;
100
101is(ref $a, "Oscalar");
102
103$b++;
104
105is(ref $b, "Oscalar");
106is($a, "087");
107is($b, "88");
108is(ref $a, "Oscalar");
109
110package Oscalar;
111$dummy=bless \$dummy;		# Now cache of method should be reloaded
112package main;
113
114$b=$a;
115$b++;
116
117is(ref $b, "Oscalar");
118is($a, "087");
119is($b, "88");
120is(ref $a, "Oscalar");
121
122undef $b;			# Destroying updates tables too...
123
124eval q[package Oscalar; use overload ('++' => sub { $ {$_[0]} += 2; $_[0] } ) ];
125
126$b=$a;
127
128is(ref $a, "Oscalar");
129
130$b++;
131
132is(ref $b, "Oscalar");
133is($a, "087");
134is($b, "89");
135is(ref $a, "Oscalar");
136
137package Oscalar;
138$dummy=bless \$dummy;		# Now cache of method should be reloaded
139package main;
140
141$b++;
142
143is(ref $b, "Oscalar");
144is($a, "087");
145is($b, "91");
146is(ref $a, "Oscalar");
147
148$b=$a;
149$b++;
150
151is(ref $b, "Oscalar");
152is($a, "087");
153is($b, "89");
154is(ref $a, "Oscalar");
155
156
157ok($b? 1:0);
158
159eval q[ package Oscalar; use overload ('=' => sub {$main::copies++;
160						   package Oscalar;
161						   local $new=$ {$_[0]};
162						   bless \$new } ) ];
163
164$b=new Oscalar "$a";
165
166is(ref $b, "Oscalar");
167is($a, "087");
168is($b, "087");
169is(ref $a, "Oscalar");
170
171$b++;
172
173is(ref $b, "Oscalar");
174is($a, "087");
175is($b, "89");
176is(ref $a, "Oscalar");
177is($copies, undef);
178
179$b+=1;
180
181is(ref $b, "Oscalar");
182is($a, "087");
183is($b, "90");
184is(ref $a, "Oscalar");
185is($copies, undef);
186
187$b=$a;
188$b+=1;
189
190is(ref $b, "Oscalar");
191is($a, "087");
192is($b, "88");
193is(ref $a, "Oscalar");
194is($copies, undef);
195
196$b=$a;
197$b++;
198
199is(ref $b, "Oscalar");
200is($a, "087");
201is($b, "89");
202is(ref $a, "Oscalar");
203is($copies, 1);
204
205eval q[package Oscalar; use overload ('+=' => sub {$ {$_[0]} += 3*$_[1];
206						   $_[0] } ) ];
207$c=new Oscalar;			# Cause rehash
208
209$b=$a;
210$b+=1;
211
212is(ref $b, "Oscalar");
213is($a, "087");
214is($b, "90");
215is(ref $a, "Oscalar");
216is($copies, 2);
217
218$b+=$b;
219
220is(ref $b, "Oscalar");
221is($b, "360");
222is($copies, 2);
223$b=-$b;
224
225is(ref $b, "Oscalar");
226is($b, "-360");
227is($copies, 2);
228
229$b=abs($b);
230
231is(ref $b, "Oscalar");
232is($b, "360");
233is($copies, 2);
234
235$b=abs($b);
236
237is(ref $b, "Oscalar");
238is($b, "360");
239is($copies, 2);
240
241eval q[package Oscalar;
242       use overload ('x' => sub {new Oscalar ( $_[2] ? "_.$_[1]._" x $ {$_[0]}
243					      : "_.${$_[0]}._" x $_[1])}) ];
244
245$a=new Oscalar "yy";
246$a x= 3;
247is($a, "_.yy.__.yy.__.yy._");
248
249eval q[package Oscalar;
250       use overload ('.' => sub {new Oscalar ( $_[2] ?
251					      "_.$_[1].__.$ {$_[0]}._"
252					      : "_.$ {$_[0]}.__.$_[1]._")}) ];
253
254$a=new Oscalar "xx";
255
256is("b${a}c", "_._.b.__.xx._.__.c._");
257
258# Check inheritance of overloading;
259{
260  package OscalarI;
261  @ISA = 'Oscalar';
262}
263
264$aI = new OscalarI "$a";
265is(ref $aI, "OscalarI");
266is("$aI", "xx");
267is($aI, "xx");
268is("b${aI}c", "_._.b.__.xx._.__.c._");
269
270# Here we test that both "no overload" and
271# blessing to a package update hash
272
273eval "package Oscalar; no overload '.'";
274
275is("b${a}", "bxx");
276$x="1";
277bless \$x, Oscalar;
278is("b${a}c", "bxxc");
279new Oscalar 1;
280is("b${a}c", "bxxc");
281
282# Negative overloading:
283
284$na = eval { ~$a };
285like($@, qr/no method found/);
286
287# Check AUTOLOADING:
288
289*Oscalar::AUTOLOAD =
290  sub { *{"Oscalar::$AUTOLOAD"} = sub {"_!_" . shift() . "_!_"} ;
291	goto &{"Oscalar::$AUTOLOAD"}};
292
293eval "package Oscalar; sub comple; use overload '~' => 'comple'";
294
295$na = eval { ~$a };
296is($@, '');
297
298bless \$x, Oscalar;
299
300$na = eval { ~$a };		# Hash updated
301warn "'$na', $@" if $@;
302ok !$@;
303is($na, '_!_xx_!_');
304
305$na = 0;
306
307$na = eval { ~$aI };
308like($@, '');
309
310bless \$x, OscalarI;
311
312$na = eval { ~$aI };
313print $@;
314
315ok(!$@);
316is($na, '_!_xx_!_');
317
318eval "package Oscalar; sub rshft; use overload '>>' => 'rshft'";
319
320$na = eval { $aI >> 1 };
321is($@, '');
322
323bless \$x, OscalarI;
324
325$na = 0;
326
327$na = eval { $aI >> 1 };
328print $@;
329
330ok(!$@);
331is($na, '_!_xx_!_');
332
333# warn overload::Method($a, '0+'), "\n";
334is(overload::Method($a, '0+'), \&Oscalar::numify);
335is(overload::Method($aI,'0+'), \&Oscalar::numify);
336ok(overload::Overloaded($aI));
337ok(!overload::Overloaded('overload'));
338
339ok(! defined overload::Method($aI, '<<'));
340ok(! defined overload::Method($a, '<'));
341
342like (overload::StrVal($aI), qr/^OscalarI=SCALAR\(0x[\da-fA-F]+\)$/);
343is(overload::StrVal(\$aI), "@{[\$aI]}");
344
345# Check overloading by methods (specified deep in the ISA tree).
346{
347  package OscalarII;
348  @ISA = 'OscalarI';
349  sub Oscalar::lshft {"_<<_" . shift() . "_<<_"}
350  eval "package OscalarI; use overload '<<' => 'lshft', '|' => 'lshft'";
351}
352
353$aaII = "087";
354$aII = \$aaII;
355bless $aII, 'OscalarII';
356bless \$fake, 'OscalarI';		# update the hash
357is(($aI | 3), '_<<_xx_<<_');
358# warn $aII << 3;
359is(($aII << 3), '_<<_087_<<_');
360
361{
362  BEGIN { $int = 7; overload::constant 'integer' => sub {$int++; shift}; }
363  $out = 2**10;
364}
365is($int, 9);
366is($out, 1024);
367is($int, 9);
368{
369  BEGIN { overload::constant 'integer' => sub {$int++; shift()+1}; }
370  eval q{$out = 42};
371}
372is($int, 10);
373is($out, 43);
374
375$foo = 'foo';
376$foo1 = 'f\'o\\o';
377{
378  BEGIN { $q = $qr = 7;
379	  overload::constant 'q' => sub {$q++; push @q, shift, ($_[1] || 'none'); shift},
380			     'qr' => sub {$qr++; push @qr, shift, ($_[1] || 'none'); shift}; }
381  $out = 'foo';
382  $out1 = 'f\'o\\o';
383  $out2 = "a\a$foo,\,";
384  /b\b$foo.\./;
385}
386
387is($out, 'foo');
388is($out, $foo);
389is($out1, 'f\'o\\o');
390is($out1, $foo1);
391is($out2, "a\afoo,\,");
392is("@q", "foo q f'o\\\\o q a\\a qq ,\\, qq");
393is($q, 11);
394is("@qr", "b\\b qq .\\. qq");
395is($qr, 9);
396
397{
398  $_ = '!<b>!foo!<-.>!';
399  BEGIN { overload::constant 'q' => sub {push @q1, shift, ($_[1] || 'none'); "_<" . (shift) . ">_"},
400			     'qr' => sub {push @qr1, shift, ($_[1] || 'none'); "!<" . (shift) . ">!"}; }
401  $out = 'foo';
402  $out1 = 'f\'o\\o';
403  $out2 = "a\a$foo,\,";
404  $res = /b\b$foo.\./;
405  $a = <<EOF;
406oups
407EOF
408  $b = <<'EOF';
409oups1
410EOF
411  $c = bareword;
412  m'try it';
413  s'first part'second part';
414  s/yet another/tail here/;
415  tr/A-Z/a-z/;
416}
417
418is($out, '_<foo>_');
419is($out1, '_<f\'o\\o>_');
420is($out2, "_<a\a>_foo_<,\,>_");
421is("@q1", "foo q f'o\\\\o q a\\a qq ,\\, qq oups
422 qq oups1
423 q second part q tail here s A-Z tr a-z tr");
424is("@qr1", "b\\b qq .\\. qq try it q first part q yet another qq");
425is($res, 1);
426is($a, "_<oups
427>_");
428is($b, "_<oups1
429>_");
430is($c, "bareword");
431
432{
433  package symbolic;		# Primitive symbolic calculator
434  use overload nomethod => \&wrap, '""' => \&str, '0+' => \&num,
435      '=' => \&cpy, '++' => \&inc, '--' => \&dec;
436
437  sub new { shift; bless ['n', @_] }
438  sub cpy {
439    my $self = shift;
440    bless [@$self], ref $self;
441  }
442  sub inc { $_[0] = bless ['++', $_[0], 1]; }
443  sub dec { $_[0] = bless ['--', $_[0], 1]; }
444  sub wrap {
445    my ($obj, $other, $inv, $meth) = @_;
446    if ($meth eq '++' or $meth eq '--') {
447      @$obj = ($meth, (bless [@$obj]), 1); # Avoid circular reference
448      return $obj;
449    }
450    ($obj, $other) = ($other, $obj) if $inv;
451    bless [$meth, $obj, $other];
452  }
453  sub str {
454    my ($meth, $a, $b) = @{+shift};
455    $a = 'u' unless defined $a;
456    if (defined $b) {
457      "[$meth $a $b]";
458    } else {
459      "[$meth $a]";
460    }
461  }
462  my %subr = ( 'n' => sub {$_[0]} );
463  foreach my $op (split " ", $overload::ops{with_assign}) {
464    $subr{$op} = $subr{"$op="} = eval "sub {shift() $op shift()}";
465  }
466  my @bins = qw(binary 3way_comparison num_comparison str_comparison);
467  foreach my $op (split " ", "@overload::ops{ @bins }") {
468    $subr{$op} = eval "sub {shift() $op shift()}";
469  }
470  foreach my $op (split " ", "@overload::ops{qw(unary func)}") {
471    $subr{$op} = eval "sub {$op shift()}";
472  }
473  $subr{'++'} = $subr{'+'};
474  $subr{'--'} = $subr{'-'};
475
476  sub num {
477    my ($meth, $a, $b) = @{+shift};
478    my $subr = $subr{$meth}
479      or die "Do not know how to ($meth) in symbolic";
480    $a = $a->num if ref $a eq __PACKAGE__;
481    $b = $b->num if ref $b eq __PACKAGE__;
482    $subr->($a,$b);
483  }
484  sub TIESCALAR { my $pack = shift; $pack->new(@_) }
485  sub FETCH { shift }
486  sub nop {  }		# Around a bug
487  sub vars { my $p = shift; tie($_, $p), $_->nop foreach @_; }
488  sub STORE {
489    my $obj = shift;
490    $#$obj = 1;
491    $obj->[1] = shift;
492  }
493}
494
495{
496  my $foo = new symbolic 11;
497  my $baz = $foo++;
498  is((sprintf "%d", $foo), '12');
499  is((sprintf "%d", $baz), '11');
500  my $bar = $foo;
501  $baz = ++$foo;
502  is((sprintf "%d", $foo), '13');
503  is((sprintf "%d", $bar), '12');
504  is((sprintf "%d", $baz), '13');
505  my $ban = $foo;
506  $baz = ($foo += 1);
507  is((sprintf "%d", $foo), '14');
508  is((sprintf "%d", $bar), '12');
509  is((sprintf "%d", $baz), '14');
510  is((sprintf "%d", $ban), '13');
511  $baz = 0;
512  $baz = $foo++;
513  is((sprintf "%d", $foo), '15');
514  is((sprintf "%d", $baz), '14');
515  is("$foo", '[++ [+= [++ [++ [n 11] 1] 1] 1] 1]');
516}
517
518{
519  my $iter = new symbolic 2;
520  my $side = new symbolic 1;
521  my $cnt = $iter;
522
523  while ($cnt) {
524    $cnt = $cnt - 1;		# The "simple" way
525    $side = (sqrt(1 + $side**2) - 1)/$side;
526  }
527  my $pi = $side*(2**($iter+2));
528  is("$side", '[/ [- [sqrt [+ 1 [** [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1] [n 1]] 2]]] 1] [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1] [n 1]]]');
529  is((sprintf "%f", $pi), '3.182598');
530}
531
532{
533  my $iter = new symbolic 2;
534  my $side = new symbolic 1;
535  my $cnt = $iter;
536
537  while ($cnt--) {
538    $side = (sqrt(1 + $side**2) - 1)/$side;
539  }
540  my $pi = $side*(2**($iter+2));
541  is("$side", '[/ [- [sqrt [+ 1 [** [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1] [n 1]] 2]]] 1] [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1] [n 1]]]');
542  is((sprintf "%f", $pi), '3.182598');
543}
544
545{
546  my ($a, $b);
547  symbolic->vars($a, $b);
548  my $c = sqrt($a**2 + $b**2);
549  $a = 3; $b = 4;
550  is((sprintf "%d", $c), '5');
551  $a = 12; $b = 5;
552  is((sprintf "%d", $c), '13');
553}
554
555{
556  package symbolic1;		# Primitive symbolic calculator
557  # Mutator inc/dec
558  use overload nomethod => \&wrap, '""' => \&str, '0+' => \&num, '=' => \&cpy;
559
560  sub new { shift; bless ['n', @_] }
561  sub cpy {
562    my $self = shift;
563    bless [@$self], ref $self;
564  }
565  sub wrap {
566    my ($obj, $other, $inv, $meth) = @_;
567    if ($meth eq '++' or $meth eq '--') {
568      @$obj = ($meth, (bless [@$obj]), 1); # Avoid circular reference
569      return $obj;
570    }
571    ($obj, $other) = ($other, $obj) if $inv;
572    bless [$meth, $obj, $other];
573  }
574  sub str {
575    my ($meth, $a, $b) = @{+shift};
576    $a = 'u' unless defined $a;
577    if (defined $b) {
578      "[$meth $a $b]";
579    } else {
580      "[$meth $a]";
581    }
582  }
583  my %subr = ( 'n' => sub {$_[0]} );
584  foreach my $op (split " ", $overload::ops{with_assign}) {
585    $subr{$op} = $subr{"$op="} = eval "sub {shift() $op shift()}";
586  }
587  my @bins = qw(binary 3way_comparison num_comparison str_comparison);
588  foreach my $op (split " ", "@overload::ops{ @bins }") {
589    $subr{$op} = eval "sub {shift() $op shift()}";
590  }
591  foreach my $op (split " ", "@overload::ops{qw(unary func)}") {
592    $subr{$op} = eval "sub {$op shift()}";
593  }
594  $subr{'++'} = $subr{'+'};
595  $subr{'--'} = $subr{'-'};
596
597  sub num {
598    my ($meth, $a, $b) = @{+shift};
599    my $subr = $subr{$meth}
600      or die "Do not know how to ($meth) in symbolic";
601    $a = $a->num if ref $a eq __PACKAGE__;
602    $b = $b->num if ref $b eq __PACKAGE__;
603    $subr->($a,$b);
604  }
605  sub TIESCALAR { my $pack = shift; $pack->new(@_) }
606  sub FETCH { shift }
607  sub vars { my $p = shift; tie($_, $p) foreach @_; }
608  sub STORE {
609    my $obj = shift;
610    $#$obj = 1;
611    $obj->[1] = shift;
612  }
613}
614
615{
616  my $foo = new symbolic1 11;
617  my $baz = $foo++;
618  is((sprintf "%d", $foo), '12');
619  is((sprintf "%d", $baz), '11');
620  my $bar = $foo;
621  $baz = ++$foo;
622  is((sprintf "%d", $foo), '13');
623  is((sprintf "%d", $bar), '12');
624  is((sprintf "%d", $baz), '13');
625  my $ban = $foo;
626  $baz = ($foo += 1);
627  is((sprintf "%d", $foo), '14');
628  is((sprintf "%d", $bar), '12');
629  is((sprintf "%d", $baz), '14');
630  is((sprintf "%d", $ban), '13');
631  $baz = 0;
632  $baz = $foo++;
633  is((sprintf "%d", $foo), '15');
634  is((sprintf "%d", $baz), '14');
635  is("$foo", '[++ [+= [++ [++ [n 11] 1] 1] 1] 1]');
636}
637
638{
639  my $iter = new symbolic1 2;
640  my $side = new symbolic1 1;
641  my $cnt = $iter;
642
643  while ($cnt) {
644    $cnt = $cnt - 1;		# The "simple" way
645    $side = (sqrt(1 + $side**2) - 1)/$side;
646  }
647  my $pi = $side*(2**($iter+2));
648  is("$side", '[/ [- [sqrt [+ 1 [** [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1] [n 1]] 2]]] 1] [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1] [n 1]]]');
649  is((sprintf "%f", $pi), '3.182598');
650}
651
652{
653  my $iter = new symbolic1 2;
654  my $side = new symbolic1 1;
655  my $cnt = $iter;
656
657  while ($cnt--) {
658    $side = (sqrt(1 + $side**2) - 1)/$side;
659  }
660  my $pi = $side*(2**($iter+2));
661  is("$side", '[/ [- [sqrt [+ 1 [** [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1] [n 1]] 2]]] 1] [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1] [n 1]]]');
662  is((sprintf "%f", $pi), '3.182598');
663}
664
665{
666  my ($a, $b);
667  symbolic1->vars($a, $b);
668  my $c = sqrt($a**2 + $b**2);
669  $a = 3; $b = 4;
670  is((sprintf "%d", $c), '5');
671  $a = 12; $b = 5;
672  is((sprintf "%d", $c), '13');
673}
674
675{
676  package two_face;		# Scalars with separate string and
677                                # numeric values.
678  sub new { my $p = shift; bless [@_], $p }
679  use overload '""' => \&str, '0+' => \&num, fallback => 1;
680  sub num {shift->[1]}
681  sub str {shift->[0]}
682}
683
684{
685  my $seven = new two_face ("vii", 7);
686  is((sprintf "seven=$seven, seven=%d, eight=%d", $seven, $seven+1),
687	'seven=vii, seven=7, eight=8');
688  is(scalar ($seven =~ /i/), '1');
689}
690
691{
692  package sorting;
693  use overload 'cmp' => \&comp;
694  sub new { my ($p, $v) = @_; bless \$v, $p }
695  sub comp { my ($x,$y) = @_; ($$x * 3 % 10) <=> ($$y * 3 % 10) or $$x cmp $$y }
696}
697{
698  my @arr = map sorting->new($_), 0..12;
699  my @sorted1 = sort @arr;
700  my @sorted2 = map $$_, @sorted1;
701  is("@sorted2", '0 10 7 4 1 11 8 5 12 2 9 6 3');
702}
703{
704  package iterator;
705  use overload '<>' => \&iter;
706  sub new { my ($p, $v) = @_; bless \$v, $p }
707  sub iter { my ($x) = @_; return undef if $$x < 0; return $$x--; }
708}
709
710{
711  my $iter = iterator->new(5);
712  my $acc = '';
713  my $out;
714  $acc .= " $out" while $out = <${iter}>;
715  is($acc, ' 5 4 3 2 1 0');
716  $iter = iterator->new(5);
717  is(scalar <${iter}>, '5');
718  $acc = '';
719  $acc .= " $out" while $out = <$iter>;
720  is($acc, ' 4 3 2 1 0');
721}
722{
723  package deref;
724  use overload '%{}' => \&hderef, '&{}' => \&cderef,
725    '*{}' => \&gderef, '${}' => \&sderef, '@{}' => \&aderef;
726  sub new { my ($p, $v) = @_; bless \$v, $p }
727  sub deref {
728    my ($self, $key) = (shift, shift);
729    my $class = ref $self;
730    bless $self, 'deref::dummy'; # Disable overloading of %{}
731    my $out = $self->{$key};
732    bless $self, $class;	# Restore overloading
733    $out;
734  }
735  sub hderef {shift->deref('h')}
736  sub aderef {shift->deref('a')}
737  sub cderef {shift->deref('c')}
738  sub gderef {shift->deref('g')}
739  sub sderef {shift->deref('s')}
740}
741{
742  my $deref = bless { h => { foo => 5 , fake => 23 },
743		      c => sub {return shift() + 34},
744		      's' => \123,
745		      a => [11..13],
746		      g => \*srt,
747		    }, 'deref';
748  # Hash:
749  my @cont = sort %$deref;
750  if ("\t" eq "\011") { # ASCII
751      is("@cont", '23 5 fake foo');
752  }
753  else {                # EBCDIC alpha-numeric sort order
754      is("@cont", 'fake foo 23 5');
755  }
756  my @keys = sort keys %$deref;
757  is("@keys", 'fake foo');
758  my @val = sort values %$deref;
759  is("@val", '23 5');
760  is($deref->{foo}, 5);
761  is(defined $deref->{bar}, '');
762  my $key;
763  @keys = ();
764  push @keys, $key while $key = each %$deref;
765  @keys = sort @keys;
766  is("@keys", 'fake foo');
767  is(exists $deref->{bar}, '');
768  is(exists $deref->{foo}, 1);
769  # Code:
770  is($deref->(5), 39);
771  is(&$deref(6), 40);
772  sub xxx_goto { goto &$deref }
773  is(xxx_goto(7), 41);
774  my $srt = bless { c => sub {$b <=> $a}
775		  }, 'deref';
776  *srt = \&$srt;
777  my @sorted = sort srt 11, 2, 5, 1, 22;
778  is("@sorted", '22 11 5 2 1');
779  # Scalar
780  is($$deref, 123);
781  # Code
782  @sorted = sort $srt 11, 2, 5, 1, 22;
783  is("@sorted", '22 11 5 2 1');
784  # Array
785  is("@$deref", '11 12 13');
786  is($#$deref, '2');
787  my $l = @$deref;
788  is($l, 3);
789  is($deref->[2], '13');
790  $l = pop @$deref;
791  is($l, 13);
792  $l = 1;
793  is($deref->[$l], '12');
794  # Repeated dereference
795  my $double = bless { h => $deref,
796		     }, 'deref';
797  is($double->{foo}, 5);
798}
799
800{
801  package two_refs;
802  use overload '%{}' => \&gethash, '@{}' => sub { ${shift()} };
803  sub new {
804    my $p = shift;
805    bless \ [@_], $p;
806  }
807  sub gethash {
808    my %h;
809    my $self = shift;
810    tie %h, ref $self, $self;
811    \%h;
812  }
813
814  sub TIEHASH { my $p = shift; bless \ shift, $p }
815  my %fields;
816  my $i = 0;
817  $fields{$_} = $i++ foreach qw{zero one two three};
818  sub STORE {
819    my $self = ${shift()};
820    my $key = $fields{shift()};
821    defined $key or die "Out of band access";
822    $$self->[$key] = shift;
823  }
824  sub FETCH {
825    my $self = ${shift()};
826    my $key = $fields{shift()};
827    defined $key or die "Out of band access";
828    $$self->[$key];
829  }
830}
831
832my $bar = new two_refs 3,4,5,6;
833$bar->[2] = 11;
834is($bar->{two}, 11);
835$bar->{three} = 13;
836is($bar->[3], 13);
837
838{
839  package two_refs_o;
840  @ISA = ('two_refs');
841}
842
843$bar = new two_refs_o 3,4,5,6;
844$bar->[2] = 11;
845is($bar->{two}, 11);
846$bar->{three} = 13;
847is($bar->[3], 13);
848
849{
850  package two_refs1;
851  use overload '%{}' => sub { ${shift()}->[1] },
852               '@{}' => sub { ${shift()}->[0] };
853  sub new {
854    my $p = shift;
855    my $a = [@_];
856    my %h;
857    tie %h, $p, $a;
858    bless \ [$a, \%h], $p;
859  }
860  sub gethash {
861    my %h;
862    my $self = shift;
863    tie %h, ref $self, $self;
864    \%h;
865  }
866
867  sub TIEHASH { my $p = shift; bless \ shift, $p }
868  my %fields;
869  my $i = 0;
870  $fields{$_} = $i++ foreach qw{zero one two three};
871  sub STORE {
872    my $a = ${shift()};
873    my $key = $fields{shift()};
874    defined $key or die "Out of band access";
875    $a->[$key] = shift;
876  }
877  sub FETCH {
878    my $a = ${shift()};
879    my $key = $fields{shift()};
880    defined $key or die "Out of band access";
881    $a->[$key];
882  }
883}
884
885$bar = new two_refs_o 3,4,5,6;
886$bar->[2] = 11;
887is($bar->{two}, 11);
888$bar->{three} = 13;
889is($bar->[3], 13);
890
891{
892  package two_refs1_o;
893  @ISA = ('two_refs1');
894}
895
896$bar = new two_refs1_o 3,4,5,6;
897$bar->[2] = 11;
898is($bar->{two}, 11);
899$bar->{three} = 13;
900is($bar->[3], 13);
901
902{
903  package B;
904  use overload bool => sub { ${+shift} };
905}
906
907my $aaa;
908{ my $bbbb = 0; $aaa = bless \$bbbb, B }
909
910is !$aaa, 1;
911
912unless ($aaa) {
913  pass();
914} else {
915  fail();
916}
917
918# check that overload isn't done twice by join
919{ my $c = 0;
920  package Join;
921  use overload '""' => sub { $c++ };
922  my $x = join '', bless([]), 'pq', bless([]);
923  main::is $x, '0pq1';
924};
925
926# Test module-specific warning
927{
928    # check the Odd number of arguments for overload::constant warning
929    my $a = "" ;
930    local $SIG{__WARN__} = sub {$a = $_[0]} ;
931    $x = eval ' overload::constant "integer" ; ' ;
932    is($a, "");
933    use warnings 'overload' ;
934    $x = eval ' overload::constant "integer" ; ' ;
935    like($a, qr/^Odd number of arguments for overload::constant at/);
936}
937
938{
939    # check the '$_[0]' is not an overloadable type warning
940    my $a = "" ;
941    local $SIG{__WARN__} = sub {$a = $_[0]} ;
942    $x = eval ' overload::constant "fred" => sub {} ; ' ;
943    is($a, "");
944    use warnings 'overload' ;
945    $x = eval ' overload::constant "fred" => sub {} ; ' ;
946    like($a, qr/^'fred' is not an overloadable type at/);
947}
948
949{
950    # check the '$_[1]' is not a code reference warning
951    my $a = "" ;
952    local $SIG{__WARN__} = sub {$a = $_[0]} ;
953    $x = eval ' overload::constant "integer" => 1; ' ;
954    is($a, "");
955    use warnings 'overload' ;
956    $x = eval ' overload::constant "integer" => 1; ' ;
957    like($a, qr/^'1' is not a code reference at/);
958}
959
960{
961    # check the invalid argument warning [perl #74098]
962    my $a = "" ;
963    local $SIG{__WARN__} = sub {$a = $_[0]} ;
964    $x = eval ' use overload "~|_|~" => sub{} ' ;
965    eval ' no overload "~|_|~" ' ;
966    is($a, "");
967    use warnings 'overload' ;
968    $x = eval ' use overload "~|_|~" => sub{} ' ;
969    like($a, qr/^overload arg '~\|_\|~' is invalid at \(eval \d+\) line /,
970	'invalid arg warning');
971    undef $a;
972    eval ' no overload "~|_|~" ' ;
973    like($a, qr/^overload arg '~\|_\|~' is invalid at \(eval \d+\) line /,
974	'invalid arg warning');
975}
976
977{
978  my $c = 0;
979  package ov_int1;
980  use overload '""'    => sub { 3+shift->[0] },
981               '0+'    => sub { 10+shift->[0] },
982               'int'   => sub { 100+shift->[0] };
983  sub new {my $p = shift; bless [shift], $p}
984
985  package ov_int2;
986  use overload '""'    => sub { 5+shift->[0] },
987               '0+'    => sub { 30+shift->[0] },
988               'int'   => sub { 'ov_int1'->new(1000+shift->[0]) };
989  sub new {my $p = shift; bless [shift], $p}
990
991  package noov_int;
992  use overload '""'    => sub { 2+shift->[0] },
993               '0+'    => sub { 9+shift->[0] };
994  sub new {my $p = shift; bless [shift], $p}
995
996  package main;
997
998  my $x = new noov_int 11;
999  my $int_x = int $x;
1000  main::is("$int_x", 20);
1001  $x = new ov_int1 31;
1002  $int_x = int $x;
1003  main::is("$int_x", 131);
1004  $x = new ov_int2 51;
1005  $int_x = int $x;
1006  main::is("$int_x", 1054);
1007}
1008
1009# make sure that we don't infinitely recurse
1010{
1011  my $c = 0;
1012  package Recurse;
1013  use overload '""'    => sub { shift },
1014               '0+'    => sub { shift },
1015               'bool'  => sub { shift },
1016               fallback => 1;
1017  my $x = bless([]);
1018  # For some reason beyond me these have to be oks rather than likes.
1019  main::ok("$x" =~ /Recurse=ARRAY/);
1020  main::ok($x);
1021  main::ok($x+0 =~ qr/Recurse=ARRAY/);
1022}
1023
1024# BugID 20010422.003
1025package Foo;
1026
1027use overload
1028  'bool' => sub { return !$_[0]->is_zero() || undef; }
1029;
1030
1031sub is_zero
1032  {
1033  my $self = shift;
1034  return $self->{var} == 0;
1035  }
1036
1037sub new
1038  {
1039  my $class = shift;
1040  my $self =  {};
1041  $self->{var} = shift;
1042  bless $self,$class;
1043  }
1044
1045package main;
1046
1047use strict;
1048
1049my $r = Foo->new(8);
1050$r = Foo->new(0);
1051
1052is(($r || 0), 0);
1053
1054package utf8_o;
1055
1056use overload
1057  '""'  =>  sub { return $_[0]->{var}; }
1058  ;
1059
1060sub new
1061  {
1062    my $class = shift;
1063    my $self =  {};
1064    $self->{var} = shift;
1065    bless $self,$class;
1066  }
1067
1068package main;
1069
1070
1071my $utfvar = new utf8_o 200.2.1;
1072is("$utfvar", 200.2.1); # 223 - stringify
1073is("a$utfvar", "a".200.2.1); # 224 - overload via sv_2pv_flags
1074
1075# 225..227 -- more %{} tests.  Hangs in 5.6.0, okay in later releases.
1076# Basically this example implements strong encapsulation: if Hderef::import()
1077# were to eval the overload code in the caller's namespace, the privatisation
1078# would be quite transparent.
1079package Hderef;
1080use overload '%{}' => sub { (caller(0))[0] eq 'Foo' ? $_[0] : die "zap" };
1081package Foo;
1082@Foo::ISA = 'Hderef';
1083sub new { bless {}, shift }
1084sub xet { @_ == 2 ? $_[0]->{$_[1]} :
1085	  @_ == 3 ? ($_[0]->{$_[1]} = $_[2]) : undef }
1086package main;
1087my $a = Foo->new;
1088$a->xet('b', 42);
1089is ($a->xet('b'), 42);
1090ok (!defined eval { $a->{b} });
1091like ($@, qr/zap/);
1092
1093{
1094   package t229;
1095   use overload '='  => sub { 42 },
1096                '++' => sub { my $x = ${$_[0]}; $_[0] };
1097   sub new { my $x = 42; bless \$x }
1098
1099   my $warn;
1100   {
1101     local $SIG{__WARN__} = sub { $warn++ };
1102      my $x = t229->new;
1103      my $y = $x;
1104      eval { $y++ };
1105   }
1106   main::ok (!$warn);
1107}
1108
1109{
1110    my ($int, $out1, $out2);
1111    {
1112        BEGIN { $int = 0; overload::constant 'integer' => sub {$int++; 17}; }
1113        $out1 = 0;
1114        $out2 = 1;
1115    }
1116    is($int,  2,  "#24313");	# 230
1117    is($out1, 17, "#24313");	# 231
1118    is($out2, 17, "#24313");	# 232
1119}
1120
1121{
1122    package perl31793;
1123    use overload cmp => sub { 0 };
1124    package perl31793_fb;
1125    use overload cmp => sub { 0 }, fallback => 1;
1126    package main;
1127    my $o  = bless [], 'perl31793';
1128    my $of = bless [], 'perl31793_fb';
1129    my $no = bless [], 'no_overload';
1130    like(overload::StrVal(\"scalar"), qr/^SCALAR\(0x[0-9a-f]+\)$/);
1131    like(overload::StrVal([]),        qr/^ARRAY\(0x[0-9a-f]+\)$/);
1132    like(overload::StrVal({}),        qr/^HASH\(0x[0-9a-f]+\)$/);
1133    like(overload::StrVal(sub{1}),    qr/^CODE\(0x[0-9a-f]+\)$/);
1134    like(overload::StrVal(\*GLOB),    qr/^GLOB\(0x[0-9a-f]+\)$/);
1135    like(overload::StrVal(\$o),       qr/^REF\(0x[0-9a-f]+\)$/);
1136    like(overload::StrVal(qr/a/),     qr/^Regexp=REGEXP\(0x[0-9a-f]+\)$/);
1137    like(overload::StrVal($o),        qr/^perl31793=ARRAY\(0x[0-9a-f]+\)$/);
1138    like(overload::StrVal($of),       qr/^perl31793_fb=ARRAY\(0x[0-9a-f]+\)$/);
1139    like(overload::StrVal($no),       qr/^no_overload=ARRAY\(0x[0-9a-f]+\)$/);
1140}
1141
1142{
1143    package Numify;
1144    use overload (qw(0+ numify fallback 1));
1145
1146    sub new {
1147	my $val = $_[1];
1148	bless \$val, $_[0];
1149    }
1150
1151    sub numify { ${$_[0]} }
1152}
1153
1154# These all check that overloaded values, rather than reference addresses,
1155# are what are getting tested.
1156my ($two, $one, $un, $deux) = map {new Numify $_} 2, 1, 1, 2;
1157my ($ein, $zwei) = (1, 2);
1158
1159my %map = (one => 1, un => 1, ein => 1, deux => 2, two => 2, zwei => 2);
1160foreach my $op (qw(<=> == != < <= > >=)) {
1161    foreach my $l (keys %map) {
1162	foreach my $r (keys %map) {
1163	    my $ocode = "\$$l $op \$$r";
1164	    my $rcode = "$map{$l} $op $map{$r}";
1165
1166	    my $got = eval $ocode;
1167	    die if $@;
1168	    my $expect = eval $rcode;
1169	    die if $@;
1170	    is ($got, $expect, $ocode) or print "# $rcode\n";
1171	}
1172    }
1173}
1174{
1175    # check that overloading works in regexes
1176    {
1177	package Foo493;
1178	use overload
1179	    '""' => sub { "^$_[0][0]\$" },
1180	    '.'  => sub {
1181		    bless [
1182			     $_[2]
1183			    ? (ref $_[1] ? $_[1][0] : $_[1]) . ':' .$_[0][0]
1184			    : $_[0][0] . ':' . (ref $_[1] ? $_[1][0] : $_[1])
1185		    ], 'Foo493'
1186			};
1187    }
1188
1189    my $a = bless [ "a" ], 'Foo493';
1190    like('a', qr/$a/);
1191    like('x:a', qr/x$a/);
1192    like('x:a:=', qr/x$a=$/);
1193    like('x:a:a:=', qr/x$a$a=$/);
1194
1195}
1196
1197{
1198    {
1199        package QRonly;
1200        use overload qr => sub { qr/x/ }, fallback => 1;
1201    }
1202    {
1203        my $x = bless [], "QRonly";
1204
1205        # like tries to be too clever, and decides that $x-stringified
1206        # doesn't look like a regex
1207        ok("x" =~ $x, "qr-only matches");
1208        ok("y" !~ $x, "qr-only doesn't match what it shouldn't");
1209        ok("x" =~ /^(??{$x})$/, "qr-only with ?? matches");
1210        ok("y" !~ /^(??{$x})$/, "qr-only with ?? doesn't match what it shouldn't");
1211        ok("xx" =~ /x$x/, "qr-only matches with concat");
1212        like("$x", qr/^QRonly=ARRAY/, "qr-only doesn't have string overload");
1213
1214        my $qr = bless qr/y/, "QRonly";
1215        ok("x" =~ $qr, "qr with qr-overload uses overload");
1216        ok("y" !~ $qr, "qr with qr-overload uses overload");
1217	ok("x" =~ /^(??{$qr})$/, "qr with qr-overload with ?? uses overload");
1218	ok("y" !~ /^(??{$qr})$/, "qr with qr-overload with ?? uses overload");
1219        is("$qr", "".qr/y/, "qr with qr-overload stringify");
1220
1221        my $rx = $$qr;
1222        ok("y" =~ $rx, "bare rx with qr-overload doesn't overload match");
1223        ok("x" !~ $rx, "bare rx with qr-overload doesn't overload match");
1224        ok("y" =~ /^(??{$rx})$/, "bare rx with qr-overload with ?? doesn't overload match");
1225        ok("x" !~ /^(??{$rx})$/, "bare rx with qr-overload with ?? doesn't overload match");
1226        is("$rx", "".qr/y/, "bare rx with qr-overload stringify");
1227    }
1228    {
1229        package QRandSTR;
1230        use overload qr => sub { qr/x/ }, q/""/ => sub { "y" };
1231    }
1232    {
1233        my $x = bless [], "QRandSTR";
1234        ok("x" =~ $x, "qr+str uses qr for match");
1235        ok("y" !~ $x, "qr+str uses qr for match");
1236        ok("xx" =~ /x$x/, "qr+str uses qr for match with concat");
1237        is("$x", "y", "qr+str uses str for stringify");
1238
1239        my $qr = bless qr/z/, "QRandSTR";
1240        is("$qr", "y", "qr with qr+str uses str for stringify");
1241        ok("xx" =~ /x$x/, "qr with qr+str uses qr for match");
1242
1243        my $rx = $$qr;
1244        ok("z" =~ $rx, "bare rx with qr+str doesn't overload match");
1245        is("$rx", "".qr/z/, "bare rx with qr+str doesn't overload stringify");
1246    }
1247    {
1248        package QRany;
1249        use overload qr => sub { $_[0]->(@_) };
1250
1251        package QRself;
1252        use overload qr => sub { $_[0] };
1253    }
1254    {
1255        my $rx = bless sub { ${ qr/x/ } }, "QRany";
1256        ok("x" =~ $rx, "qr overload accepts a bare rx");
1257        ok("y" !~ $rx, "qr overload accepts a bare rx");
1258
1259        my $str = bless sub { "x" }, "QRany";
1260        ok(!eval { "x" =~ $str }, "qr overload doesn't accept a string");
1261        like($@, qr/^Overloaded qr did not return a REGEXP/, "correct error");
1262
1263        my $oqr = bless qr/z/, "QRandSTR";
1264        my $oqro = bless sub { $oqr }, "QRany";
1265        ok("z" =~ $oqro, "qr overload doesn't recurse");
1266
1267        my $qrs = bless qr/z/, "QRself";
1268        ok("z" =~ $qrs, "qr overload can return self");
1269    }
1270    {
1271        package STRonly;
1272        use overload q/""/ => sub { "x" };
1273
1274        package STRonlyFB;
1275        use overload q/""/ => sub { "x" }, fallback => 1;
1276    }
1277    {
1278        my $fb = bless [], "STRonlyFB";
1279        ok("x" =~ $fb, "qr falls back to \"\"");
1280        ok("y" !~ $fb, "qr falls back to \"\"");
1281
1282        my $nofb = bless [], "STRonly";
1283        ok("x" =~ $nofb, "qr falls back even without fallback");
1284        ok("y" !~ $nofb, "qr falls back even without fallback");
1285    }
1286}
1287
1288{
1289    my $twenty_three = 23;
1290    # Check that constant overloading propagates into evals
1291    BEGIN { overload::constant integer => sub { 23 } }
1292    is(eval "17", $twenty_three);
1293}
1294
1295{
1296    package Sklorsh;
1297    use overload
1298	bool     => sub { shift->is_cool };
1299
1300    sub is_cool {
1301	$_[0]->{name} eq 'cool';
1302    }
1303
1304    sub delete {
1305	undef %{$_[0]};
1306	bless $_[0], 'Brap';
1307	return 1;
1308    }
1309
1310    sub delete_with_self {
1311	my $self = shift;
1312	undef %$self;
1313	bless $self, 'Brap';
1314	return 1;
1315    }
1316
1317    package Brap;
1318
1319    1;
1320
1321    package main;
1322
1323    my $obj;
1324    $obj = bless {name => 'cool'}, 'Sklorsh';
1325    $obj->delete;
1326    ok(eval {if ($obj) {1}; 1}, $@ || 'reblessed into nonexistent namespace');
1327
1328    $obj = bless {name => 'cool'}, 'Sklorsh';
1329    $obj->delete_with_self;
1330    ok (eval {if ($obj) {1}; 1}, $@);
1331
1332    my $a = $b = {name => 'hot'};
1333    bless $b, 'Sklorsh';
1334    is(ref $a, 'Sklorsh');
1335    is(ref $b, 'Sklorsh');
1336    ok(!$b, "Expect overloaded boolean");
1337    ok(!$a, "Expect overloaded boolean");
1338}
1339
1340{
1341    package Flrbbbbb;
1342    use overload
1343	bool	 => sub { shift->{truth} eq 'yes' },
1344	'0+'	 => sub { shift->{truth} eq 'yes' ? '1' : '0' },
1345	'!'	 => sub { shift->{truth} eq 'no' },
1346	fallback => 1;
1347
1348    sub new { my $class = shift; bless { truth => shift }, $class }
1349
1350    package main;
1351
1352    my $yes = Flrbbbbb->new('yes');
1353    my $x;
1354    $x = 1 if $yes;			is($x, 1);
1355    $x = 2 unless $yes;			is($x, 1);
1356    $x = 3 if !$yes;			is($x, 1);
1357    $x = 4 unless !$yes;		is($x, 4);
1358
1359    my $no = Flrbbbbb->new('no');
1360    $x = 0;
1361    $x = 1 if $no;			is($x, 0);
1362    $x = 2 unless $no;			is($x, 2);
1363    $x = 3 if !$no;			is($x, 3);
1364    $x = 4 unless !$no;			is($x, 3);
1365
1366    $x = 0;
1367    $x = 1 if !$no && $yes;		is($x, 1);
1368    $x = 2 unless !$no && $yes;		is($x, 1);
1369    $x = 3 if $no || !$yes;		is($x, 1);
1370    $x = 4 unless $no || !$yes;		is($x, 4);
1371
1372    $x = 0;
1373    $x = 1 if !$no || !$yes;		is($x, 1);
1374    $x = 2 unless !$no || !$yes;	is($x, 1);
1375    $x = 3 if !$no && !$yes;		is($x, 1);
1376    $x = 4 unless !$no && !$yes;	is($x, 4);
1377}
1378
1379{
1380    use Scalar::Util 'weaken';
1381
1382    package Shklitza;
1383    use overload '""' => sub {"CLiK KLAK"};
1384
1385    package Ksshfwoom;
1386
1387    package main;
1388
1389    my ($obj, $ref);
1390    $obj = bless do {my $a; \$a}, 'Shklitza';
1391    $ref = $obj;
1392
1393    is ("$obj", "CLiK KLAK");
1394    is ("$ref", "CLiK KLAK");
1395
1396    weaken $ref;
1397    is ("$ref", "CLiK KLAK");
1398
1399    bless $obj, 'Ksshfwoom';
1400
1401    like ($obj, qr/^Ksshfwoom=/);
1402    like ($ref, qr/^Ksshfwoom=/);
1403
1404    undef $obj;
1405    is ($ref, undef);
1406}
1407
1408{
1409    package bit;
1410    # bit operations have overloadable assignment variants too
1411
1412    sub new { bless \$_[1], $_[0] }
1413
1414    use overload
1415          "&=" => sub { bit->new($_[0]->val . ' & ' . $_[1]->val) },
1416          "^=" => sub { bit->new($_[0]->val . ' ^ ' . $_[1]->val) },
1417          "|"  => sub { bit->new($_[0]->val . ' | ' . $_[1]->val) }, # |= by fallback
1418          ;
1419
1420    sub val { ${$_[0]} }
1421
1422    package main;
1423
1424    my $a = bit->new(my $va = 'a');
1425    my $b = bit->new(my $vb = 'b');
1426
1427    $a &= $b;
1428    is($a->val, 'a & b', "overloaded &= works");
1429
1430    my $c = bit->new(my $vc = 'c');
1431
1432    $b ^= $c;
1433    is($b->val, 'b ^ c', "overloaded ^= works");
1434
1435    my $d = bit->new(my $vd = 'd');
1436
1437    $c |= $d;
1438    is($c->val, 'c | d', "overloaded |= (by fallback) works");
1439}
1440
1441{
1442    # comparison operators with nomethod (bug 41546)
1443    my $warning = "";
1444    my $method;
1445
1446    package nomethod_false;
1447    use overload nomethod => sub { $method = 'nomethod'; 0 };
1448
1449    package nomethod_true;
1450    use overload nomethod => sub { $method= 'nomethod'; 'true' };
1451
1452    package main;
1453    local $^W = 1;
1454    local $SIG{__WARN__} = sub { $warning = $_[0] };
1455
1456    my $f = bless [], 'nomethod_false';
1457    ($warning, $method) = ("", "");
1458    is($f eq 'whatever', 0, 'nomethod makes eq return 0');
1459    is($method, 'nomethod');
1460
1461    my $t = bless [], 'nomethod_true';
1462    ($warning, $method) = ("", "");
1463    is($t eq 'whatever', 'true', 'nomethod makes eq return "true"');
1464    is($method, 'nomethod');
1465    is($warning, "", 'nomethod eq need not return number');
1466
1467    eval q{
1468        package nomethod_false;
1469        use overload cmp => sub { $method = 'cmp'; 0 };
1470    };
1471    $f = bless [], 'nomethod_false';
1472    ($warning, $method) = ("", "");
1473    ok($f eq 'whatever', 'eq falls back to cmp (nomethod not called)');
1474    is($method, 'cmp');
1475
1476    eval q{
1477        package nomethod_true;
1478        use overload cmp => sub { $method = 'cmp'; 'true' };
1479    };
1480    $t = bless [], 'nomethod_true';
1481    ($warning, $method) = ("", "");
1482    ok($t eq 'whatever', 'eq falls back to cmp (nomethod not called)');
1483    is($method, 'cmp');
1484    like($warning, qr/isn't numeric/, 'cmp should return number');
1485
1486}
1487
1488{
1489    # nomethod called for '!' after attempted fallback
1490    my $nomethod_called = 0;
1491
1492    package nomethod_not;
1493    use overload nomethod => sub { $nomethod_called = 'yes'; };
1494
1495    package main;
1496    my $o = bless [], 'nomethod_not';
1497    my $res = ! $o;
1498
1499    is($nomethod_called, 'yes', "nomethod() is called for '!'");
1500    is($res, 'yes', "nomethod(..., '!') return value propagates");
1501}
1502
1503{
1504    # Subtle bug pre 5.10, as a side effect of the overloading flag being
1505    # stored on the reference rather than the referent. Despite the fact that
1506    # objects can only be accessed via references (even internally), the
1507    # referent actually knows that it's blessed, not the references. So taking
1508    # a new, unrelated, reference to it gives an object. However, the
1509    # overloading-or-not flag was on the reference prior to 5.10, and taking
1510    # a new reference didn't (use to) copy it.
1511
1512    package kayo;
1513
1514    use overload '""' => sub {${$_[0]}};
1515
1516    sub Pie {
1517	return "$_[0], $_[1]";
1518    }
1519
1520    package main;
1521
1522    my $class = 'kayo';
1523    my $string = 'bam';
1524    my $crunch_eth = bless \$string, $class;
1525
1526    is("$crunch_eth", $string);
1527    is ($crunch_eth->Pie("Meat"), "$string, Meat");
1528
1529    my $wham_eth = \$string;
1530
1531    is("$wham_eth", $string,
1532       'This reference did not have overloading in 5.8.8 and earlier');
1533    is ($crunch_eth->Pie("Apple"), "$string, Apple");
1534
1535    my $class = ref $wham_eth;
1536    $class =~ s/=.*//;
1537
1538    # Bless it back into its own class!
1539    bless $wham_eth, $class;
1540
1541    is("$wham_eth", $string);
1542    is ($crunch_eth->Pie("Blackbird"), "$string, Blackbird");
1543}
1544
1545{
1546    package numify_int;
1547    use overload "0+" => sub { $_[0][0] += 1; 42 };
1548    package numify_self;
1549    use overload "0+" => sub { $_[0][0]++; $_[0] };
1550    package numify_other;
1551    use overload "0+" => sub { $_[0][0]++; $_[0][1] = bless [], 'numify_int' };
1552    package numify_by_fallback;
1553    use overload fallback => 1;
1554
1555    package main;
1556    my $o = bless [], 'numify_int';
1557    is(int($o), 42, 'numifies to integer');
1558    is($o->[0], 1, 'int() numifies only once');
1559
1560    my $aref = [];
1561    my $num_val = int($aref);
1562    my $r = bless $aref, 'numify_self';
1563    is(int($r), $num_val, 'numifies to self');
1564    is($r->[0], 1, 'int() numifies once when returning self');
1565
1566    my $s = bless [], 'numify_other';
1567    is(int($s), 42, 'numifies to numification of other object');
1568    is($s->[0], 1, 'int() numifies once when returning other object');
1569    is($s->[1][0], 1, 'returned object numifies too');
1570
1571    my $m = bless $aref, 'numify_by_fallback';
1572    is(int($m), $num_val, 'numifies to usual reference value');
1573    is(abs($m), $num_val, 'numifies to usual reference value');
1574    is(-$m, -$num_val, 'numifies to usual reference value');
1575    is(0+$m, $num_val, 'numifies to usual reference value');
1576    is($m+0, $num_val, 'numifies to usual reference value');
1577    is($m+$m, 2*$num_val, 'numifies to usual reference value');
1578    is(0-$m, -$num_val, 'numifies to usual reference value');
1579    is(1*$m, $num_val, 'numifies to usual reference value');
1580    is(int($m/1), $num_val, 'numifies to usual reference value');
1581    is($m%100, $num_val%100, 'numifies to usual reference value');
1582    is($m**1, $num_val, 'numifies to usual reference value');
1583
1584    is(abs($aref), $num_val, 'abs() of ref');
1585    is(-$aref, -$num_val, 'negative of ref');
1586    is(0+$aref, $num_val, 'ref addition');
1587    is($aref+0, $num_val, 'ref addition');
1588    is($aref+$aref, 2*$num_val, 'ref addition');
1589    is(0-$aref, -$num_val, 'subtraction of ref');
1590    is(1*$aref, $num_val, 'multiplicaton of ref');
1591    is(int($aref/1), $num_val, 'division of ref');
1592    is($aref%100, $num_val%100, 'modulo of ref');
1593    is($aref**1, $num_val, 'exponentiation of ref');
1594}
1595
1596{
1597    package CopyConstructorFallback;
1598    use overload
1599        '++'        => sub { "$_[0]"; $_[0] },
1600        fallback    => 1;
1601    sub new { bless {} => shift }
1602
1603    package main;
1604
1605    my $o = CopyConstructorFallback->new;
1606    my $x = $o++; # would segfault
1607    my $y = ++$o;
1608    is($x, $o, "copy constructor falls back to assignment (postinc)");
1609    is($y, $o, "copy constructor falls back to assignment (preinc)");
1610}
1611
1612# only scalar 'x' should currently overload
1613
1614{
1615    package REPEAT;
1616
1617    my ($x,$n, $nm);
1618
1619    use overload
1620	'x'        => sub { $x++; 1 },
1621	'0+'       => sub { $n++; 1 },
1622	'nomethod' => sub { $nm++; 1 },
1623	'fallback' => 0,
1624    ;
1625
1626    my $s = bless {};
1627
1628    package main;
1629
1630    my @a;
1631    my $count = 3;
1632
1633    ($x,$n,$nm) = (0,0,0);
1634    @a = ((1,2,$s) x $count);
1635    is("$x-$n-$nm", "0-0-0", 'repeat 1');
1636
1637    ($x,$n,$nm) = (0,0,0);
1638    @a = ((1,$s,3) x $count);
1639    is("$x-$n-$nm", "0-0-0", 'repeat 2');
1640
1641    ($x,$n,$nm) = (0,0,0);
1642    @a = ((1,2,3) x $s);
1643    is("$x-$n-$nm", "0-1-0", 'repeat 3');
1644}
1645
1646
1647
1648# RT #57012: magic items need to have mg_get() called before testing for
1649# overload. Lack of this means that overloaded values returned by eg a
1650# tied array didn't call overload methods.
1651# We test here both a tied array and scalar, since the implementation of
1652# tied  arrays (and hashes) is such that in rvalue context, mg_get is
1653# called prior to executing the op, while it isn't for a tied scalar.
1654# We also check that return values are correctly tainted.
1655# We try against two overload packages; one has all expected methods, the
1656# other uses only fallback methods.
1657
1658{
1659
1660    # @tests holds a list of test cases. Each elem is an array ref with
1661    # the following entries:
1662    #
1663    #  * the value that the overload method should return
1664    #
1665    #  * the expression to be evaled. %s is replaced with the
1666    #       variable being tested ($ta[0], $ts, or $plain)
1667    #
1668    #  * a string listing what functions we expect to be called.
1669    #       Each method appends its name in parentheses, so "(=)(+)" means
1670    #       we expect the copy constructor and then the add method to be
1671    #       called.
1672    #
1673    #  * like above, but what should be called for the fallback-only test
1674    #      (in this case, nomethod() identifies itself as "(NM:*)" where *
1675    #      is the op).  If this value is undef, fallback tests are skipped.
1676    #
1677    #  * An array ref of expected counts of calls to FETCH/STORE.
1678    #      The first three values are:
1679    #         1. the expected number of FETCHs for a tied array
1680    #         2. the expected number of FETCHs for a tied scalar
1681    #         3. the expected number of STOREs
1682    #       If there are a further three elements present, then
1683    #       these represent the expected counts for the fallback
1684    #       version of the tests. If absent, they are assumed to
1685    #       be the same as for the full method test
1686    #
1687    #  * Under the taint version of the tests,  whether we expect
1688    #       the result to be tainted (for example comparison ops
1689    #       like '==' don't return a tainted value, even if their
1690    #       args are.
1691    my @tests;
1692
1693    my %subs;
1694    my $funcs;
1695    my $use_int;
1696
1697    BEGIN {
1698	# A note on what methods to expect to be called, and
1699	# how many times FETCH/STORE is called:
1700	#
1701	# Mutating ops (+=, ++ etc) trigger a copy ('='), since
1702	# the code can't distinguish between something that's been copied:
1703	#    $a = foo->new(0); $b = $a; refcnt($$b) == 2
1704	# and overloaded objects stored in ties which will have extra
1705	# refcounts due to the tied_obj magic and entries on the tmps
1706	# stack when returning from FETCH etc. So we always copy.
1707
1708	# This accounts for a '=', and an extra STORE.
1709	# We also have a FETCH returning the final value from the eval,
1710	# plus a FETCH in the overload subs themselves: ($_[0][0])
1711	# triggers one. However, tied aggregates have a mechanism to prevent
1712	# multiple fetches between STOREs, which means that the tied
1713	# hash skips doing a FETCH during '='.
1714
1715	for (qw(+ - * / % ** << >> & | ^)) {
1716	    my $op = $_;
1717	    $op = '%%' if $op eq '%';
1718	    my $e = "%s $op= 3";
1719	    $subs{"$_="} = $e;
1720	    # ARRAY  FETCH: initial,        sub+=, eval-return,
1721	    # SCALAR FETCH: initial, sub=,  sub+=, eval-return,
1722	    # STORE:        copy, mutator
1723	    push @tests, [ 18, $e, "(=)($_=)", "(=)(NM:$_=)", [ 3, 4, 2 ], 1 ];
1724
1725	    $subs{$_} =
1726		"do { my \$arg = %s; \$_[2] ? (3 $op \$arg) : (\$arg $op 3) }";
1727	    # ARRAY  FETCH: initial
1728	    # SCALAR FETCH: initial eval-return,
1729	    push @tests, [ 18, "%s $op 3", "($_)", "(NM:$_)", [ 1, 2, 0 ], 1 ];
1730	    push @tests, [ 18, "3 $op %s", "($_)", "(NM:$_)", [ 1, 2, 0 ], 1 ];
1731	}
1732
1733	# these use string fallback rather than nomethod
1734	for (qw(x .)) {
1735	    my $op = $_;
1736	    my $e = "%s $op= 3";
1737	    $subs{"$_="} = $e;
1738	    # For normal case:
1739	    #   ARRAY  FETCH: initial,        sub+=, eval-return,
1740	    #   SCALAR FETCH: initial, sub=,  sub+=, eval-return,
1741	    #          STORE: copy, mutator
1742	    # for fallback, we just stringify, so eval-return and copy skipped
1743
1744	    push @tests, [ 18, $e, "(=)($_=)", '("")',
1745			    [ 3, 4, 2,     2, 3, 1 ], 1 ];
1746
1747	    $subs{$_} =
1748		"do { my \$arg = %s; \$_[2] ? (3 $op \$arg) : (\$arg $op 3) }";
1749	    # ARRAY  FETCH: initial
1750	    # SCALAR FETCH: initial eval-return,
1751	    # with fallback, we just stringify, so eval-return skipped,
1752	    #    but an extra FETCH happens in sub"", except for 'x',
1753	    #    which passes a copy of the RV to sub"", avoiding the
1754	    #    second FETCH
1755
1756	    push @tests, [ 18, "%s $op 3", "($_)", '("")',
1757			    [ 1, 2, 0,     1, ($_ eq '.' ? 2 : 1), 0 ], 1 ];
1758	    next if $_ eq 'x'; # repeat only overloads on LHS
1759	    push @tests, [ 18, "3 $op %s", "($_)", '("")',
1760			    [ 1, 2, 0,     1, 2, 0 ], 1 ];
1761	}
1762
1763	for (qw(++ --)) {
1764	    my $pre  = "$_%s";
1765	    my $post = "%s$_";
1766	    $subs{$_} = $pre;
1767	    push @tests,
1768		# ARRAY  FETCH: initial,        sub+=, eval-return,
1769		# SCALAR FETCH: initial, sub=,  sub+=, eval-return,
1770		# STORE:        copy, mutator
1771		[ 18, $pre, "(=)($_)(\"\")", "(=)(NM:$_)(\"\")", [ 3, 4, 2 ], 1 ],
1772		# ARRAY  FETCH: initial,        sub+=
1773		# SCALAR FETCH: initial, sub=,  sub+=
1774		# STORE:        copy, mutator
1775		[ 18, $post, "(=)($_)(\"\")", "(=)(NM:$_)(\"\")", [ 2, 3, 2 ], 1 ];
1776	}
1777
1778	# For the non-mutator ops, we have a initial FETCH,
1779	# an extra FETCH within the sub itself for the scalar option,
1780	# and no STOREs
1781
1782	for (qw(< <= >  >= == != lt le gt ge eq ne)) {
1783	    my $e = "%s $_ 3";
1784	    $subs{$_} = $e;
1785	    push @tests, [ 3, $e, "($_)", "(NM:$_)", [ 1, 2, 0 ], 0 ];
1786	}
1787	for (qw(<=> cmp)) {
1788	    my $e = "%s $_ 3";
1789	    $subs{$_} = $e;
1790	    push @tests, [ 3, $e, "($_)", "(NM:$_)", [ 1, 2, 0 ], 1 ];
1791	}
1792	for (qw(atan2)) {
1793	    my $e = "$_ %s, 3";
1794	    $subs{$_} = $e;
1795	    push @tests, [ 18, $e, "($_)", "(NM:$_)", [ 1, 2, 0 ], 1 ];
1796	}
1797	for (qw(cos sin exp abs log sqrt int ~)) {
1798	    my $e = "$_(%s)";
1799	    $subs{$_} = $e;
1800	    push @tests, [ 1.23, $e, "($_)",
1801		    ($_ eq 'int' ? '(0+)' : "(NM:$_)") , [ 1, 2, 0 ], 1 ];
1802	}
1803	for (qw(!)) {
1804	    my $e = "$_(%s)";
1805	    $subs{$_} = $e;
1806	    push @tests, [ 1.23, $e, "($_)", '(0+)', [ 1, 2, 0 ], 0 ];
1807	}
1808	for (qw(-)) {
1809	    my $e = "$_(%s)";
1810	    $subs{neg} = $e;
1811	    push @tests, [ 18, $e, '(neg)', '(NM:neg)', [ 1, 2, 0 ], 1 ];
1812	}
1813	my $e = '(%s) ? 1 : 0';
1814	$subs{bool} = $e;
1815	push @tests, [ 18, $e, '(bool)', '(0+)', [ 1, 2, 0 ], 0 ];
1816
1817	# note: this is testing unary qr, not binary =~
1818	$subs{qr} = '(qr/%s/)';
1819	push @tests, [ "abc", '"abc" =~ (%s)', '(qr)', '("")', [ 1, 2, 0 ], 0 ];
1820	push @tests, [ chr 256, 'chr(256) =~ (%s)', '(qr)', '("")',
1821	                                                  [ 1, 2, 0 ], 0 ];
1822
1823	$e = '"abc" ~~ (%s)';
1824	$subs{'~~'} = $e;
1825	push @tests, [ "abc", $e, '(~~)', '(NM:~~)', [ 1, 1, 0 ], 0 ];
1826
1827	$subs{'-X'} = 'do { my $f = (%s);'
1828		    . '$_[1] eq "r" ? (-r ($f)) :'
1829		    . '$_[1] eq "e" ? (-e ($f)) :'
1830		    . '$_[1] eq "f" ? (-f ($f)) :'
1831		    . '$_[1] eq "l" ? (-l ($f)) :'
1832		    . '$_[1] eq "t" ? (-t ($f)) :'
1833		    . '$_[1] eq "T" ? (-T ($f)) : 0;}';
1834	# Note - we don't care what these file tests return, as
1835	# long as the tied and untied versions return the same value.
1836	# The flags below are chosen to test all uses of tryAMAGICftest_MG
1837	for (qw(r e f l t T)) {
1838	    push @tests, [ 'TEST', "-$_ (%s)", '(-X)', '("")', [ 1, 2, 0 ], 0 ];
1839	}
1840
1841	$subs{'${}'} = '%s';
1842	push @tests, [ do {my $s=99; \$s}, '${%s}', '(${})', undef, [ 1, 1, 0 ], 0 ];
1843
1844	# we skip testing '@{}' here because too much of this test
1845	# framework involves array dereferences!
1846
1847	$subs{'%{}'} = '%s';
1848	push @tests, [ {qw(a 1 b 2 c 3)}, 'join "", sort keys %%{%s}',
1849			'(%{})', undef, [ 1, 1, 0 ], 0 ];
1850
1851	$subs{'&{}'} = '%s';
1852	push @tests, [ sub {99}, 'do {&{%s} for 1,2}',
1853			    '(&{})(&{})', undef, [ 2, 2, 0 ], 0 ];
1854
1855	our $RT57012A = 88;
1856	our $RT57012B;
1857	$subs{'*{}'} = '%s';
1858	push @tests, [ \*RT57012A, '*RT57012B = *{%s}; our $RT57012B',
1859		'(*{})', undef, [ 1, 1, 0 ], 0 ];
1860
1861	my $iter_text = ("some random text\n" x 100) . $^X;
1862	open my $iter_fh, '<', \$iter_text
1863	    or die "open of \$iter_text gave ($!)\n";
1864	$subs{'<>'} = '<$iter_fh>';
1865	push @tests, [ $iter_fh, '<%s>', '(<>)', undef, [ 1, 1, 0 ], 1 ];
1866	push @tests, [ $iter_fh,
1867		      'local *CORE::GLOBAL::glob = sub {}; eval q|<%s>|',
1868		      '(<>)', undef, [ 1, 1, 0 ], 1 ];
1869
1870	# eval should do tie, overload on its arg before checking taint */
1871	push @tests, [ '1;', 'eval q(eval %s); $@ =~ /Insecure/',
1872		'("")', '("")', [ 1, 2, 0 ], 0 ];
1873
1874
1875	for my $sub (keys %subs) {
1876	    no warnings 'experimental::smartmatch';
1877	    my $term = $subs{$sub};
1878	    my $t = sprintf $term, '$_[0][0]';
1879	    my $e ="sub { \$funcs .= '($sub)'; my \$r; if (\$use_int) {"
1880		. "use integer; \$r = ($t) } else { \$r = ($t) } \$r }";
1881	    $subs{$sub} = eval $e;
1882	    die "Compiling sub gave error:\n<$e>\n<$@>\n" if $@;
1883	}
1884    }
1885
1886    my $fetches;
1887    my $stores;
1888
1889    package RT57012_OV;
1890
1891    use overload
1892	%subs,
1893	"="   => sub { $funcs .= '(=)';  bless [ $_[0][0] ] },
1894	'0+'  => sub { $funcs .= '(0+)'; 0 + $_[0][0] },
1895	'""'  => sub { $funcs .= '("")'; "$_[0][0]"   },
1896	;
1897
1898    package RT57012_OV_FB; # only contains fallback conversion functions
1899
1900    use overload
1901	"="   => sub { $funcs .= '(=)';  bless [ $_[0][0] ] },
1902	'0+'  => sub { $funcs .= '(0+)'; 0 + $_[0][0] },
1903	'""'  => sub { $funcs .= '("")'; "$_[0][0]"   },
1904	"nomethod" => sub {
1905			$funcs .= "(NM:$_[3])";
1906			my $e = defined($_[1])
1907				? $_[3] eq 'atan2'
1908				    ? $_[2]
1909				       ? "atan2(\$_[1],\$_[0][0])"
1910				       : "atan2(\$_[0][0],\$_[1])"
1911				    : $_[2]
1912					? "\$_[1] $_[3] \$_[0][0]"
1913					: "\$_[0][0] $_[3] \$_[1]"
1914				: $_[3] eq 'neg'
1915				    ? "-\$_[0][0]"
1916				    : "$_[3](\$_[0][0])";
1917			my $r;
1918			no warnings 'experimental::smartmatch';
1919			if ($use_int) {
1920			    use integer; $r = eval $e;
1921			}
1922			else {
1923			    $r = eval $e;
1924			}
1925			::diag("eval of nomethod <$e> gave <$@>") if $@;
1926			$r;
1927		    }
1928
1929	;
1930
1931    package RT57012_TIE_S;
1932
1933    my $tie_val;
1934    sub TIESCALAR { bless [ bless [ $tie_val ], $_[1] ] }
1935    sub FETCH     { $fetches++; $_[0][0] }
1936    sub STORE     { $stores++;  $_[0][0] = $_[1] }
1937
1938    package RT57012_TIE_A;
1939
1940    sub TIEARRAY  { bless [] }
1941    sub FETCH     { $fetches++; $_[0][0] }
1942    sub STORE     { $stores++;  $_[0][$_[1]] = $_[2] }
1943
1944    package main;
1945
1946    for my $test (@tests) {
1947	my ($val, $sub_term, $exp_funcs, $exp_fb_funcs,
1948	    $exp_counts, $exp_taint) = @$test;
1949
1950	my $tainted_val;
1951	{
1952	    # create tainted version of $val (unless its a ref)
1953	    my $t = substr($^X,0,0);
1954	    my $t0 = $t."0";
1955	    my $val1 = $val; # use a copy to avoid stringifying original
1956	    $tainted_val = ref($val1) ? $val :
1957			($val1 =~ /^[\d\.]+$/) ? $val+$t0 : $val.$t;
1958	}
1959	$tie_val = $tainted_val;
1960
1961	for my $int ('', 'use integer; ') {
1962	    $use_int = ($int ne '');
1963	    my $plain = $tainted_val;
1964	    my $plain_term = $int . sprintf $sub_term, '$plain';
1965	    my $exp = do {no warnings 'experimental::smartmatch'; eval $plain_term };
1966	    diag("eval of plain_term <$plain_term> gave <$@>") if $@;
1967	    is(tainted($exp), $exp_taint,
1968			"<$plain_term> taint of expected return");
1969
1970	    for my $ov_pkg (qw(RT57012_OV RT57012_OV_FB)) {
1971		next if $ov_pkg eq 'RT57012_OV_FB'
1972			and  not defined $exp_fb_funcs;
1973		my ($exp_fetch_a, $exp_fetch_s, $exp_store) =
1974		    ($ov_pkg eq 'RT57012_OV' || @$exp_counts < 4)
1975			? @$exp_counts[0,1,2]
1976			: @$exp_counts[3,4,5];
1977
1978		tie my $ts, 'RT57012_TIE_S', $ov_pkg;
1979		tie my @ta, 'RT57012_TIE_A';
1980		$ta[0]    = bless [ $tainted_val ], $ov_pkg;
1981		my $oload = bless [ $tainted_val ], $ov_pkg;
1982
1983		for my $var ('$ta[0]', '$ts', '$oload',
1984			    ($sub_term eq '<%s>' ? '${ts}' : ())
1985		) {
1986
1987		    $funcs = '';
1988		    $fetches = 0;
1989		    $stores = 0;
1990
1991		    my $res_term  = $int . sprintf $sub_term, $var;
1992		    my $desc =  "<$res_term> $ov_pkg" ;
1993		    my $res = do { no warnings 'experimental::smartmatch'; eval $res_term };
1994		    diag("eval of res_term $desc gave <$@>") if $@;
1995		    # uniquely, the inc/dec ops return the original
1996		    # ref rather than a copy, so stringify it to
1997		    # find out if its tainted
1998		    $res = "$res" if $res_term =~ /\+\+|--/;
1999		    is(tainted($res), $exp_taint,
2000			    "$desc taint of result return");
2001		    is($res, $exp, "$desc return value");
2002		    my $fns =($ov_pkg eq 'RT57012_OV_FB')
2003				? $exp_fb_funcs : $exp_funcs;
2004		    if ($var eq '$oload' && $res_term !~ /oload(\+\+|--)/) {
2005			# non-tied overloading doesn't trigger a copy
2006			# except for post inc/dec
2007			$fns =~ s/^\(=\)//;
2008		    }
2009		    is($funcs, $fns, "$desc methods called");
2010		    next if $var eq '$oload';
2011		    my $exp_fetch = ($var eq '$ts') ?
2012			    $exp_fetch_s : $exp_fetch_a;
2013		    is($fetches, $exp_fetch, "$desc FETCH count");
2014		    is($stores, $exp_store, "$desc STORE count");
2015
2016		}
2017
2018	    }
2019	}
2020    }
2021}
2022
2023# Test overload from the main package
2024fresh_perl_is
2025 '$^W = 1; use overload q\""\ => sub {"ning"}; print bless []',
2026 'ning',
2027  { switches => ['-wl'], stderr => 1 },
2028 'use overload from the main package'
2029;
2030
2031{
2032    package blessed_methods;
2033    use overload '+' => sub {};
2034    bless overload::Method __PACKAGE__,'+';
2035    eval { overload::Method __PACKAGE__,'+' };
2036    ::is($@, '', 'overload::Method and blessed overload methods');
2037}
2038
2039{
2040    # fallback to 'cmp' and '<=>' with heterogeneous operands
2041    # [perl #71286]
2042    my $not_found = 'no method found';
2043    my $used = 0;
2044    package CmpBase;
2045    sub new {
2046        my $n = $_[1] || 0;
2047        bless \$n, ref $_[0] || $_[0];
2048    }
2049    sub cmp {
2050        $used = \$_[0];
2051        (${$_[0]} <=> ${$_[1]}) * ($_[2] ? -1 : 1);
2052    }
2053
2054    package NCmp;
2055    use base 'CmpBase';
2056    use overload '<=>' => 'cmp';
2057
2058    package SCmp;
2059    use base 'CmpBase';
2060    use overload 'cmp' => 'cmp';
2061
2062    package main;
2063    my $n = NCmp->new(5);
2064    my $s = SCmp->new(3);
2065    my $res;
2066
2067    eval { $res = $n > $s; };
2068    $res = $not_found if $@ =~ /$not_found/;
2069    is($res, 1, 'A>B using A<=> when B overloaded, no B<=>');
2070
2071    eval { $res = $s < $n; };
2072    $res = $not_found if $@ =~ /$not_found/;
2073    is($res, 1, 'A<B using B<=> when A overloaded, no A<=>');
2074
2075    eval { $res = $s lt $n; };
2076    $res = $not_found if $@ =~ /$not_found/;
2077    is($res, 1, 'A lt B using A:cmp when B overloaded, no B:cmp');
2078
2079    eval { $res = $n gt $s; };
2080    $res = $not_found if $@ =~ /$not_found/;
2081    is($res, 1, 'A gt B using B:cmp when A overloaded, no A:cmp');
2082
2083    my $o = NCmp->new(9);
2084    $res = $n < $o;
2085    is($used, \$n, 'A < B uses <=> from A in preference to B');
2086
2087    my $t = SCmp->new(7);
2088    $res = $s lt $t;
2089    is($used, \$s, 'A lt B uses cmp from A in preference to B');
2090}
2091
2092{
2093    # Combinatorial testing of 'fallback' and 'nomethod'
2094    # [perl #71286]
2095    package NuMB;
2096    use overload '0+' => sub { ${$_[0]}; },
2097        '""' => 'str';
2098    sub new {
2099        my $self = shift;
2100        my $n = @_ ? shift : 0;
2101        bless my $obj = \$n, ref $self || $self;
2102    }
2103    sub str {
2104        no strict qw/refs/;
2105        my $s = "(${$_[0]} ";
2106        $s .= "nomethod, " if defined ${ref($_[0]).'::(nomethod'};
2107        my $fb = ${ref($_[0]).'::()'};
2108        $s .= "fb=" . (defined $fb ? 0 + $fb : 'undef') . ")";
2109    }
2110    sub nomethod { "${$_[0]}.nomethod"; }
2111
2112    # create classes for tests
2113    package main;
2114    my @falls = (0, 'undef', 1);
2115    my @nomethods = ('', 'nomethod');
2116    my $not_found = 'no method found';
2117    for my $fall (@falls) {
2118        for my $nomethod (@nomethods) {
2119            my $nomethod_decl = $nomethod
2120                ? $nomethod . "=>'nomethod'," : '';
2121            eval qq{
2122                    package NuMB$fall$nomethod;
2123                    use base qw/NuMB/;
2124                    use overload $nomethod_decl
2125                    fallback => $fall;
2126                };
2127        }
2128    }
2129
2130    # operation and precedence of 'fallback' and 'nomethod'
2131    # for all combinations with 2 overloaded operands
2132    for my $nomethod2 (@nomethods) {
2133        for my $nomethod1 (@nomethods) {
2134            for my $fall2 (@falls) {
2135                my $pack2 = "NuMB$fall2$nomethod2";
2136                for my $fall1 (@falls) {
2137                    my $pack1 = "NuMB$fall1$nomethod1";
2138                    my ($test, $out, $exp);
2139                    eval qq{
2140                            my \$x = $pack1->new(2);
2141                            my \$y = $pack2->new(3);
2142                            \$test = "\$x" . ' * ' . "\$y";
2143                            \$out = \$x * \$y;
2144                        };
2145                    $out = $not_found if $@ =~ /$not_found/;
2146                    $exp = $nomethod1 ? '2.nomethod' :
2147                         $nomethod2 ? '3.nomethod' :
2148                         $fall1 eq '1' && $fall2 eq '1' ? 6
2149                         : $not_found;
2150                    is($out, $exp, "$test --> $exp");
2151                }
2152            }
2153        }
2154    }
2155
2156    # operation of 'fallback' and 'nomethod'
2157    # where the other operand is not overloaded
2158    for my $nomethod (@nomethods) {
2159        for my $fall (@falls) {
2160            my ($test, $out, $exp);
2161            eval qq{
2162                    my \$x = NuMB$fall$nomethod->new(2);
2163                    \$test = "\$x" . ' * 3';
2164                    \$out = \$x * 3;
2165                };
2166            $out = $not_found if $@ =~ /$not_found/;
2167            $exp = $nomethod ? '2.nomethod' :
2168                $fall eq '1' ? 6
2169                : $not_found;
2170            is($out, $exp, "$test --> $exp");
2171
2172            eval qq{
2173                    my \$x = NuMB$fall$nomethod->new(2);
2174                    \$test = '3 * ' . "\$x";
2175                    \$out = 3 * \$x;
2176                };
2177            $out = $not_found if $@ =~ /$not_found/;
2178            is($out, $exp, "$test --> $exp");
2179        }
2180    }
2181}
2182
2183# since 5.6 overloaded <> was leaving an extra arg on the stack!
2184
2185{
2186    package Iter1;
2187    use overload '<>' => sub { 11 };
2188    package main;
2189    my $a = bless [], 'Iter1';
2190    my $x;
2191    my @a = (10, ($x = <$a>), 12);
2192    is ($a[0], 10, 'Iter1: a[0]');
2193    is ($a[1], 11, 'Iter1: a[1]');
2194    is ($a[2], 12, 'Iter1: a[2]');
2195    @a = (10, ($x .= <$a>), 12);
2196    is ($a[0],   10, 'Iter1: a[0] concat');
2197    is ($a[1], 1111, 'Iter1: a[1] concat');
2198    is ($a[2],   12, 'Iter1: a[2] concat');
2199}
2200
2201# Some tests for error messages
2202{
2203    package Justus;
2204    use overload '+' => 'justice';
2205    eval {"".bless[]};
2206    ::like $@, qr/^Can't resolve method "justice" overloading "\+" in p(?x:
2207                  )ackage "Justus" at /,
2208      'Error message when explicitly named overload method does not exist';
2209
2210    package JustUs;
2211    our @ISA = 'JustYou';
2212    package JustYou { use overload '+' => 'injustice'; }
2213    "JustUs"->${\"(+"};
2214    eval {"".bless []};
2215    ::like $@, qr/^Stub found while resolving method "\?{3}" overloadin(?x:
2216                  )g "\+" in package "JustUs" at /,
2217      'Error message when sub stub is encountered';
2218}
2219
2220{
2221    # check that the right number of stringifications
2222    # and the correct un-utf8-ifying happen on regex compile
2223    package utf8_match;
2224    my $c;
2225    use overload '""' => sub { $c++; $_[0][0] ? "^\x{100}\$" : "^A\$"; };
2226    my $o = bless [0], 'utf8_match';
2227
2228    $o->[0] = 0;
2229    $c = 0;
2230    ::ok("A" =~  "^A\$",	"regex stringify utf8=0 ol=0 bytes=0");
2231    ::ok("A" =~ $o,		"regex stringify utf8=0 ol=1 bytes=0");
2232    ::is($c, 1,			"regex stringify utf8=0 ol=1 bytes=0 count");
2233
2234    $o->[0] = 1;
2235    $c = 0;
2236    ::ok("\x{100}" =~ "^\x{100}\$",
2237				"regex stringify utf8=1 ol=0 bytes=0");
2238    ::ok("\x{100}" =~ $o,	"regex stringify utf8=1 ol=1 bytes=0");
2239    ::is($c, 1,			"regex stringify utf8=1 ol=1 bytes=0 count");
2240
2241    use bytes;
2242
2243    $o->[0] = 0;
2244    $c = 0;
2245    ::ok("A" =~  "^A\$",	"regex stringify utf8=0 ol=0 bytes=1");
2246    ::ok("A" =~ $o,		"regex stringify utf8=0 ol=1 bytes=1");
2247    ::is($c, 1,			"regex stringify utf8=0 ol=1 bytes=1 count");
2248
2249    $o->[0] = 1;
2250    $c = 0;
2251    ::ok("\xc4\x80" =~ "^\x{100}\$",
2252				"regex stringify utf8=1 ol=0 bytes=1");
2253    ::ok("\xc4\x80" =~ $o,	"regex stringify utf8=1 ol=1 bytes=1");
2254    ::is($c, 1,			"regex stringify utf8=1 ol=1 bytes=1 count");
2255
2256
2257}
2258
2259# [perl #40333]
2260# overload::Overloaded should not use a ->can designed for autoloading.
2261# This example attempts to be as realistic as possible.  The o class has a
2262# default singleton object, but can have instances, too.  The proxy class
2263# represents proxies for o objects, but class methods delegate to the
2264# singleton.
2265# overload::Overloaded used to return incorrect results for proxy objects.
2266package proxy {
2267    sub new { bless [$_[1]], $_[0] }
2268    sub AUTOLOAD {
2269       our $AUTOLOAD =~ s/.*:://;
2270       &_self->$AUTOLOAD;
2271    }
2272    sub can      { SUPER::can{@_} || &_self->can($_[1]) }
2273    sub _self { ref $_[0] ? $_[0][0] : $o::singleton }
2274}
2275package o     { use overload '""' => sub { 'keck' };
2276                sub new { bless[], $_[0] }
2277                our $singleton = o->new; }
2278ok !overload::Overloaded(new proxy new o),
2279 'overload::Overloaded does not incorrectly return true for proxy classes';
2280
2281# Another test, based on the type of explosive test class for which
2282# perl #40333 was filed.
2283{
2284    package broken_can;
2285    sub can {}
2286    use overload '""' => sub {"Ahoy!"};
2287
2288    package main;
2289    my $obj = bless [], 'broken_can';
2290    ok(overload::Overloaded($obj));
2291}
2292
2293sub eleventative::cos { 'eleven' }
2294sub twelvetative::abs { 'twelve' }
2295sub thirteentative::abs { 'thirteen' }
2296sub fourteentative::abs { 'fourteen' }
2297@eleventative::ISA = twelvetative::;
2298{
2299    my $o = bless [], 'eleventative';
2300    eval 'package eleventative; use overload map +($_)x2, cos=>abs=>';
2301    is cos $o, 'eleven', 'overloading applies to object blessed before';
2302    bless [], 'eleventative';
2303    is cos $o, 'eleven',
2304      'ovrld applies to previously-blessed obj after other obj is blessed';
2305    $o = bless [], 'eleventative';
2306    *eleventative::cos = sub { 'ten' };
2307    is cos $o, 'ten', 'method changes affect overloading';
2308    @eleventative::ISA = thirteentative::;
2309    is abs $o, 'thirteen', 'isa changes affect overloading';
2310    bless $o, 'fourteentative';
2311    @fourteentative::ISA = 'eleventative';
2312    is abs $o, 'fourteen', 'isa changes can turn overloading on';
2313}
2314
2315# no overload "fallback";
2316{ package phake;
2317  use overload fallback => 1, '""' => sub { 'arakas' };
2318  no overload 'fallback';
2319}
2320$a = bless [], 'phake';
2321is "$a", "arakas",
2322    'no overload "fallback" does not stop overload from working';
2323ok !eval { () = $a eq 'mpizeli'; 1 },
2324    'no overload "fallback" resets fallback to undef on overloaded class';
2325{ package ent; use overload fallback => 0, abs => sub{};
2326  our@ISA = 'huorn';
2327  package huorn;
2328  use overload fallback => 1;
2329  package ent;
2330  no overload "fallback"; # disable previous declaration
2331}
2332$a = bless [], ent::;
2333is eval {"$a"}, overload::StrVal($a),
2334    'no overload undoes fallback declaration completetly'
2335 or diag $@;
2336
2337# inherited fallback
2338{
2339 package pervyy;
2340 our @ISA = 'vtoryy';
2341 use overload "abs" =>=> sub {};
2342 package vtoryy;
2343 use overload fallback => 1, 'sin' =>=> sub{}
2344}
2345$a = bless [], pervyy::;
2346is eval {"$a"}, overload::StrVal($a),
2347 'fallback is inherited by classes that have their own overloading'
2348 or diag $@;
2349
2350# package separators in method names
2351{
2352 package mane;
2353 use overload q\""\ => "bear::strength";
2354 use overload bool  => "bear'bouillon";
2355}
2356@bear::ISA = 'food';
2357sub food::strength { 'twine' }
2358sub food::bouillon { 0 }
2359$a = bless[], mane::;
2360is eval { "$a" }, 'twine', ':: in method name' or diag $@;
2361is eval { !$a  },   1,      "' in method name" or diag $@;
2362
2363# [perl #113050] Half of CPAN assumes fallback is under "()"
2364{
2365  package dodo;
2366  use overload '+' => sub {};
2367  no strict;
2368  *{"dodo::()"} = sub{};
2369  ${"dodo::()"} = 1;
2370}
2371$a = bless [],'dodo';
2372is eval {"$a"}, overload::StrVal($a), 'fallback is stored under "()"';
2373
2374# [perl #47119]
2375{
2376    my $context;
2377
2378    {
2379        package Splitter;
2380        use overload '<>' => \&chars;
2381
2382        sub new {
2383            my $class = shift;
2384            my ($string) = @_;
2385            bless \$string, $class;
2386        }
2387
2388        sub chars {
2389            my $self = shift;
2390            my @chars = split //, $$self;
2391            $context = wantarray;
2392            return @chars;
2393        }
2394    }
2395
2396    my $obj = Splitter->new('bar');
2397
2398    $context = 42; # not 1, '', or undef
2399
2400    my @foo = <$obj>;
2401    is($context, 1, "list context (readline list)");
2402    is(scalar(@foo), 3, "correct result (readline list)");
2403    is($foo[0], 'b', "correct result (readline list)");
2404    is($foo[1], 'a', "correct result (readline list)");
2405    is($foo[2], 'r', "correct result (readline list)");
2406
2407    $context = 42;
2408
2409    my $foo = <$obj>;
2410    ok(defined($context), "scalar context (readline scalar)");
2411    is($context, '', "scalar context (readline scalar)");
2412    is($foo, 3, "correct result (readline scalar)");
2413
2414    $context = 42;
2415
2416    <$obj>;
2417    ok(!defined($context), "void context (readline void)");
2418
2419    $context = 42;
2420
2421    my @bar = <${obj}>;
2422    is($context, 1, "list context (glob list)");
2423    is(scalar(@bar), 3, "correct result (glob list)");
2424    is($bar[0], 'b', "correct result (glob list)");
2425    is($bar[1], 'a', "correct result (glob list)");
2426    is($bar[2], 'r', "correct result (glob list)");
2427
2428    $context = 42;
2429
2430    my $bar = <${obj}>;
2431    ok(defined($context), "scalar context (glob scalar)");
2432    is($context, '', "scalar context (glob scalar)");
2433    is($bar, 3, "correct result (glob scalar)");
2434
2435    $context = 42;
2436
2437    <${obj}>;
2438    ok(!defined($context), "void context (glob void)");
2439}
2440{
2441    my $context;
2442
2443    {
2444        package StringWithContext;
2445        use overload '""' => \&stringify;
2446
2447        sub new {
2448            my $class = shift;
2449            my ($string) = @_;
2450            bless \$string, $class;
2451        }
2452
2453        sub stringify {
2454            my $self = shift;
2455            $context = wantarray;
2456            return $$self;
2457        }
2458    }
2459
2460    my $obj = StringWithContext->new('bar');
2461
2462    $context = 42;
2463
2464    my @foo = "".$obj;
2465    ok(defined($context), "scalar context (stringify list)");
2466    is($context, '', "scalar context (stringify list)");
2467    is(scalar(@foo), 1, "correct result (stringify list)");
2468    is($foo[0], 'bar', "correct result (stringify list)");
2469
2470    $context = 42;
2471
2472    my $foo = "".$obj;
2473    ok(defined($context), "scalar context (stringify scalar)");
2474    is($context, '', "scalar context (stringify scalar)");
2475    is($foo, 'bar', "correct result (stringify scalar)");
2476
2477    $context = 42;
2478
2479    "".$obj;
2480
2481    is($context, '', "scalar context (stringify void)");
2482}
2483{
2484    my ($context, $swap);
2485
2486    {
2487        package AddWithContext;
2488        use overload '+' => \&add;
2489
2490        sub new {
2491            my $class = shift;
2492            my ($num) = @_;
2493            bless \$num, $class;
2494        }
2495
2496        sub add {
2497            my $self = shift;
2498            my ($other, $swapped) = @_;
2499            $context = wantarray;
2500            $swap = $swapped;
2501            return ref($self)->new($$self + $other);
2502        }
2503
2504        sub val { ${ $_[0] } }
2505    }
2506
2507    my $obj = AddWithContext->new(6);
2508
2509    $context = $swap = 42;
2510
2511    my @foo = $obj + 7;
2512    ok(defined($context), "scalar context (add list)");
2513    is($context, '', "scalar context (add list)");
2514    ok(defined($swap), "not swapped (add list)");
2515    is($swap, '', "not swapped (add list)");
2516    is(scalar(@foo), 1, "correct result (add list)");
2517    is($foo[0]->val, 13, "correct result (add list)");
2518
2519    $context = $swap = 42;
2520
2521    @foo = 7 + $obj;
2522    ok(defined($context), "scalar context (add list swap)");
2523    is($context, '', "scalar context (add list swap)");
2524    ok(defined($swap), "swapped (add list swap)");
2525    is($swap, 1, "swapped (add list swap)");
2526    is(scalar(@foo), 1, "correct result (add list swap)");
2527    is($foo[0]->val, 13, "correct result (add list swap)");
2528
2529    $context = $swap = 42;
2530
2531    my $foo = $obj + 7;
2532    ok(defined($context), "scalar context (add scalar)");
2533    is($context, '', "scalar context (add scalar)");
2534    ok(defined($swap), "not swapped (add scalar)");
2535    is($swap, '', "not swapped (add scalar)");
2536    is($foo->val, 13, "correct result (add scalar)");
2537
2538    $context = $swap = 42;
2539
2540    my $foo = 7 + $obj;
2541    ok(defined($context), "scalar context (add scalar swap)");
2542    is($context, '', "scalar context (add scalar swap)");
2543    ok(defined($swap), "swapped (add scalar swap)");
2544    is($swap, 1, "swapped (add scalar swap)");
2545    is($foo->val, 13, "correct result (add scalar swap)");
2546
2547    $context = $swap = 42;
2548
2549    $obj + 7;
2550
2551    ok(!defined($context), "void context (add void)");
2552    ok(defined($swap), "not swapped (add void)");
2553    is($swap, '', "not swapped (add void)");
2554
2555    $context = $swap = 42;
2556
2557    7 + $obj;
2558
2559    ok(!defined($context), "void context (add void swap)");
2560    ok(defined($swap), "swapped (add void swap)");
2561    is($swap, 1, "swapped (add void swap)");
2562
2563    $obj = AddWithContext->new(6);
2564
2565    $context = $swap = 42;
2566
2567    my @foo = $obj += 7;
2568    ok(defined($context), "scalar context (add assign list)");
2569    is($context, '', "scalar context (add assign list)");
2570    ok(!defined($swap), "not swapped and autogenerated (add assign list)");
2571    is(scalar(@foo), 1, "correct result (add assign list)");
2572    is($foo[0]->val, 13, "correct result (add assign list)");
2573    is($obj->val, 13, "correct result (add assign list)");
2574
2575    $obj = AddWithContext->new(6);
2576
2577    $context = $swap = 42;
2578
2579    my $foo = $obj += 7;
2580    ok(defined($context), "scalar context (add assign scalar)");
2581    is($context, '', "scalar context (add assign scalar)");
2582    ok(!defined($swap), "not swapped and autogenerated (add assign scalar)");
2583    is($foo->val, 13, "correct result (add assign scalar)");
2584    is($obj->val, 13, "correct result (add assign scalar)");
2585
2586    $obj = AddWithContext->new(6);
2587
2588    $context = $swap = 42;
2589
2590    $obj += 7;
2591
2592    ok(defined($context), "scalar context (add assign void)");
2593    is($context, '', "scalar context (add assign void)");
2594    ok(!defined($swap), "not swapped and autogenerated (add assign void)");
2595    is($obj->val, 13, "correct result (add assign void)");
2596
2597    $obj = AddWithContext->new(6);
2598
2599    $context = $swap = 42;
2600
2601    my @foo = ++$obj;
2602    ok(defined($context), "scalar context (add incr list)");
2603    is($context, '', "scalar context (add incr list)");
2604    ok(!defined($swap), "not swapped and autogenerated (add incr list)");
2605    is(scalar(@foo), 1, "correct result (add incr list)");
2606    is($foo[0]->val, 7, "correct result (add incr list)");
2607    is($obj->val, 7, "correct result (add incr list)");
2608
2609    $obj = AddWithContext->new(6);
2610
2611    $context = $swap = 42;
2612
2613    my $foo = ++$obj;
2614    ok(defined($context), "scalar context (add incr scalar)");
2615    is($context, '', "scalar context (add incr scalar)");
2616    ok(!defined($swap), "not swapped and autogenerated (add incr scalar)");
2617    is($foo->val, 7, "correct result (add incr scalar)");
2618    is($obj->val, 7, "correct result (add incr scalar)");
2619
2620    $obj = AddWithContext->new(6);
2621
2622    $context = $swap = 42;
2623
2624    ++$obj;
2625
2626    ok(defined($context), "scalar context (add incr void)");
2627    is($context, '', "scalar context (add incr void)");
2628    ok(!defined($swap), "not swapped and autogenerated (add incr void)");
2629    is($obj->val, 7, "correct result (add incr void)");
2630}
2631
2632# [perl #113010]
2633{
2634    {
2635        package OnlyFallback;
2636        use overload fallback => 0;
2637    }
2638    {
2639        my $obj = bless {}, 'OnlyFallback';
2640        my $died = !eval { "".$obj; 1 };
2641        my $err = $@;
2642        ok($died, "fallback of 0 causes error");
2643        like($err, qr/"\.": no method found/, "correct error");
2644    }
2645
2646    {
2647        package OnlyFallbackUndef;
2648        use overload fallback => undef;
2649    }
2650    {
2651        my $obj = bless {}, 'OnlyFallbackUndef';
2652        my $died = !eval { "".$obj; 1 };
2653        my $err = $@;
2654        ok($died, "fallback of undef causes error");
2655        # this one tries falling back to stringify before dying
2656        like($err, qr/"""": no method found/, "correct error");
2657    }
2658
2659    {
2660        package OnlyFallbackTrue;
2661        use overload fallback => 1;
2662    }
2663    {
2664        my $obj = bless {}, 'OnlyFallbackTrue';
2665        my $val;
2666        my $died = !eval { $val = "".$obj; 1 };
2667        my $err = $@;
2668        ok(!$died, "fallback of 1 doesn't cause error")
2669            || diag("got error of $err");
2670        like($val, qr/^OnlyFallbackTrue=HASH\(/, "stringified correctly");
2671    }
2672}
2673
2674{
2675    # Making Regexp class overloaded: avoid infinite recursion.
2676    # Do this in a separate process since it, well, overloads Regexp!
2677    fresh_perl_is(
2678	<<'EOF',
2679package Regexp;
2680use overload q{""} => sub {$_[0] };
2681package main;
2682my $r1 = qr/1/;
2683my $r2 = qr/ABC$r1/;
2684print $r2,"\n";
2685EOF
2686	'(?^:ABC(?^:1))',
2687	{ stderr => 1 },
2688	'overloaded REGEXP'
2689    );
2690}
2691
2692{ # undefining the overload stash -- KEEP THIS TEST LAST
2693    package ant;
2694    use overload '+' => 'onion';
2695    $_ = \&overload::nil;
2696    undef %overload::;
2697    ()=0+bless[];
2698    ::ok(1, 'no crash when undefining %overload::');
2699}
2700
2701
2702# EOF
2703