7 if (($Config::Config{'extensions'} !~ m!\bList/Util\b!) ){
8 print "1..0 # Skip -- Perl configured without List::Util module\n";
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]} :
27 '%' => sub {new Oscalar
28 $_[2]? $_[1]%${$_[0]} : ${$_[0]}%$_[1]},
29 '**' => sub {new Oscalar
30 $_[2]? $_[1]**${$_[0]} : ${$_[0]}-$_[1]},
34 0+ numify) # Order of arguments insignificant
42 sub stringify { "${$_[0]}" }
43 sub numify { 0 + "${$_[0]}" } # Not needed, additional overhead
44 # comparing to direct compilation based on
50 BEGIN { require './test.pl' }
53 use Scalar::Util qw(tainted);
55 $a = new Oscalar "087";
60 is(ref $a, "Oscalar");
66 is(ref $c, "Oscalar");
72 is(ref $a, "Oscalar");
76 is(ref $b, "Oscalar");
79 is(ref $a, "Oscalar");
84 is(ref $c, "Oscalar");
87 is(ref $a, "Oscalar");
92 is(ref $b, "Oscalar");
95 is(ref $a, "Oscalar");
97 eval q[ package Oscalar; use overload ('++' => sub { $ {$_[0]}++;$_[0] } ) ];
101 is(ref $a, "Oscalar");
105 is(ref $b, "Oscalar");
108 is(ref $a, "Oscalar");
111 $dummy=bless \$dummy; # Now cache of method should be reloaded
117 is(ref $b, "Oscalar");
120 is(ref $a, "Oscalar");
122 undef $b; # Destroying updates tables too...
124 eval q[package Oscalar; use overload ('++' => sub { $ {$_[0]} += 2; $_[0] } ) ];
128 is(ref $a, "Oscalar");
132 is(ref $b, "Oscalar");
135 is(ref $a, "Oscalar");
138 $dummy=bless \$dummy; # Now cache of method should be reloaded
143 is(ref $b, "Oscalar");
146 is(ref $a, "Oscalar");
151 is(ref $b, "Oscalar");
154 is(ref $a, "Oscalar");
159 eval q[ package Oscalar; use overload ('=' => sub {$main::copies++;
161 local $new=$ {$_[0]};
166 is(ref $b, "Oscalar");
169 is(ref $a, "Oscalar");
173 is(ref $b, "Oscalar");
176 is(ref $a, "Oscalar");
181 is(ref $b, "Oscalar");
184 is(ref $a, "Oscalar");
190 is(ref $b, "Oscalar");
193 is(ref $a, "Oscalar");
199 is(ref $b, "Oscalar");
202 is(ref $a, "Oscalar");
205 eval q[package Oscalar; use overload ('+=' => sub {$ {$_[0]} += 3*"$_[1]";
207 $c=new Oscalar; # Cause rehash
212 is(ref $b, "Oscalar");
215 is(ref $a, "Oscalar");
220 is(ref $b, "Oscalar");
225 is(ref $b, "Oscalar");
231 is(ref $b, "Oscalar");
237 is(ref $b, "Oscalar");
241 eval q[package Oscalar;
242 use overload ('x' => sub {new Oscalar ( $_[2] ? "_.$_[1]._" x $ {$_[0]}
243 : "_.${$_[0]}._" x $_[1])}) ];
247 is($a, "_.yy.__.yy.__.yy._");
249 eval q[package Oscalar;
250 use overload ('.' => sub {new Oscalar ( $_[2] ?
251 "_.$_[1].__.$ {$_[0]}._"
252 : "_.$ {$_[0]}.__.$_[1]._")}) ];
256 is("b${a}c", "_._.b.__.xx._.__.c._");
258 # Check inheritance of overloading;
264 $aI = new OscalarI "$a";
265 is(ref $aI, "OscalarI");
268 is("b${aI}c", "_._.b.__.xx._.__.c._");
270 # Here we test that both "no overload" and
271 # blessing to a package update hash
273 eval "package Oscalar; no overload '.'";
278 is("b${a}c", "bxxc");
280 is("b${a}c", "bxxc");
282 # Negative overloading:
285 like($@, qr/no method found/);
290 sub { *{"Oscalar::$AUTOLOAD"} = sub {"_!_" . shift() . "_!_"} ;
291 goto &{"Oscalar::$AUTOLOAD"}};
293 eval "package Oscalar; sub comple; use overload '~' => 'comple'";
300 $na = eval { ~$a }; # Hash updated
301 warn "'$na', $@" if $@;
318 eval "package Oscalar; sub rshft; use overload '>>' => 'rshft'";
320 $na = eval { $aI >> 1 };
327 $na = eval { $aI >> 1 };
333 # warn overload::Method($a, '0+'), "\n";
334 is(overload::Method($a, '0+'), \&Oscalar::numify);
335 is(overload::Method($aI,'0+'), \&Oscalar::numify);
336 ok(overload::Overloaded($aI));
337 ok(!overload::Overloaded('overload'));
339 ok(! defined overload::Method($aI, '<<'));
340 ok(! defined overload::Method($a, '<'));
342 like (overload::StrVal($aI), qr/^OscalarI=SCALAR\(0x[\da-fA-F]+\)$/);
343 is(overload::StrVal(\$aI), "@{[\$aI]}");
345 # Check overloading by methods (specified deep in the ISA tree).
349 sub Oscalar::lshft {"_<<_" . shift() . "_<<_"}
350 eval "package OscalarI; use overload '<<' => 'lshft', '|' => 'lshft'";
355 bless $aII, 'OscalarII';
356 bless \$fake, 'OscalarI'; # update the hash
357 is(($aI | 3), '_<<_xx_<<_');
359 is(($aII << 3), '_<<_087_<<_');
362 BEGIN { $int = 7; overload::constant 'integer' => sub {$int++; shift}; }
369 BEGIN { overload::constant 'integer' => sub {$int++; shift()+1}; }
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}; }
383 $out2 = "a\a$foo,\,";
389 is($out1, 'f\'o\\o');
391 is($out2, "a\afoo,\,");
392 is("@q", "foo q f'o\\\\o q a\\a qq ,\\, qq");
394 is("@qr", "b\\b qq .\\. qq");
398 $_ = '!<b>!foo!<-.>!';
399 BEGIN { overload::constant 'q' => sub {push @q1, shift, ($_[1] || 'none'); "_<" . (shift) . ">_"},
400 'qr' => sub {push @qr1, shift, ($_[1] || 'none'); "!<" . (shift) . ">!"}; }
403 $out2 = "a\a$foo,\,";
413 s'first part'second part';
414 s/yet another/tail here/;
419 is($out1, '_<f\'o\\o>_');
420 is($out2, "_<a\a>_foo_<,\,>_");
421 is("@q1", "foo q f'o\\\\o q a\\a qq ,\\, qq oups
423 q second part q tail here s A-Z tr a-z tr");
424 is("@qr1", "b\\b qq .\\. qq try it q first part q yet another qq");
433 package symbolic; # Primitive symbolic calculator
434 use overload nomethod => \&wrap, '""' => \&str, '0+' => \&num,
435 '=' => \&cpy, '++' => \&inc, '--' => \&dec;
437 sub new { shift; bless ['n', @_] }
440 bless [@$self], ref $self;
442 sub inc { $_[0] = bless ['++', $_[0], 1]; }
443 sub dec { $_[0] = bless ['--', $_[0], 1]; }
445 my ($obj, $other, $inv, $meth) = @_;
446 if ($meth eq '++' or $meth eq '--') {
447 @$obj = ($meth, (bless [@$obj]), 1); # Avoid circular reference
450 ($obj, $other) = ($other, $obj) if $inv;
451 bless [$meth, $obj, $other];
454 my ($meth, $a, $b) = @{+shift};
455 $a = 'u' unless defined $a;
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()}";
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()}";
470 foreach my $op (split " ", "@overload::ops{qw(unary func)}") {
471 $subr{$op} = eval "sub {$op shift()}";
473 $subr{'++'} = $subr{'+'};
474 $subr{'--'} = $subr{'-'};
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__;
484 sub TIESCALAR { my $pack = shift; $pack->new(@_) }
486 sub nop { } # Around a bug
487 sub vars { my $p = shift; tie($_, $p), $_->nop foreach @_; }
496 my $foo = new symbolic 11;
498 is((sprintf "%d", $foo), '12');
499 is((sprintf "%d", $baz), '11');
502 is((sprintf "%d", $foo), '13');
503 is((sprintf "%d", $bar), '12');
504 is((sprintf "%d", $baz), '13');
507 is((sprintf "%d", $foo), '14');
508 is((sprintf "%d", $bar), '12');
509 is((sprintf "%d", $baz), '14');
510 is((sprintf "%d", $ban), '13');
513 is((sprintf "%d", $foo), '15');
514 is((sprintf "%d", $baz), '14');
515 is("$foo", '[++ [+= [++ [++ [n 11] 1] 1] 1] 1]');
519 my $iter = new symbolic 2;
520 my $side = new symbolic 1;
524 $cnt = $cnt - 1; # The "simple" way
525 $side = (sqrt(1 + $side**2) - 1)/$side;
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');
533 my $iter = new symbolic 2;
534 my $side = new symbolic 1;
538 $side = (sqrt(1 + $side**2) - 1)/$side;
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');
547 symbolic->vars($a, $b);
548 my $c = sqrt($a**2 + $b**2);
550 is((sprintf "%d", $c), '5');
552 is((sprintf "%d", $c), '13');
556 package symbolic1; # Primitive symbolic calculator
558 use overload nomethod => \&wrap, '""' => \&str, '0+' => \&num, '=' => \&cpy;
560 sub new { shift; bless ['n', @_] }
563 bless [@$self], ref $self;
566 my ($obj, $other, $inv, $meth) = @_;
567 if ($meth eq '++' or $meth eq '--') {
568 @$obj = ($meth, (bless [@$obj]), 1); # Avoid circular reference
571 ($obj, $other) = ($other, $obj) if $inv;
572 bless [$meth, $obj, $other];
575 my ($meth, $a, $b) = @{+shift};
576 $a = 'u' unless defined $a;
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()}";
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()}";
591 foreach my $op (split " ", "@overload::ops{qw(unary func)}") {
592 $subr{$op} = eval "sub {$op shift()}";
594 $subr{'++'} = $subr{'+'};
595 $subr{'--'} = $subr{'-'};
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__;
605 sub TIESCALAR { my $pack = shift; $pack->new(@_) }
607 sub vars { my $p = shift; tie($_, $p) foreach @_; }
616 my $foo = new symbolic1 11;
618 is((sprintf "%d", $foo), '12');
619 is((sprintf "%d", $baz), '11');
622 is((sprintf "%d", $foo), '13');
623 is((sprintf "%d", $bar), '12');
624 is((sprintf "%d", $baz), '13');
627 is((sprintf "%d", $foo), '14');
628 is((sprintf "%d", $bar), '12');
629 is((sprintf "%d", $baz), '14');
630 is((sprintf "%d", $ban), '13');
633 is((sprintf "%d", $foo), '15');
634 is((sprintf "%d", $baz), '14');
635 is("$foo", '[++ [+= [++ [++ [n 11] 1] 1] 1] 1]');
639 my $iter = new symbolic1 2;
640 my $side = new symbolic1 1;
644 $cnt = $cnt - 1; # The "simple" way
645 $side = (sqrt(1 + $side**2) - 1)/$side;
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');
653 my $iter = new symbolic1 2;
654 my $side = new symbolic1 1;
658 $side = (sqrt(1 + $side**2) - 1)/$side;
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');
667 symbolic1->vars($a, $b);
668 my $c = sqrt($a**2 + $b**2);
670 is((sprintf "%d", $c), '5');
672 is((sprintf "%d", $c), '13');
676 package two_face; # Scalars with separate string and
678 sub new { my $p = shift; bless [@_], $p }
679 use overload '""' => \&str, '0+' => \&num, fallback => 1;
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');
693 use overload 'cmp' => \∁
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 }
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');
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--; }
711 my $iter = iterator->new(5);
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');
719 $acc .= " $out" while $out = <$iter>;
720 is($acc, ' 4 3 2 1 0');
724 use overload '%{}' => \&hderef, '&{}' => \&cderef,
725 '*{}' => \&gderef, '${}' => \&sderef, '@{}' => \&aderef;
726 sub new { my ($p, $v) = @_; bless \$v, $p }
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
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')}
742 my $deref = bless { h => { foo => 5 , fake => 23 },
743 c => sub {return shift() + 34},
749 my @cont = sort %$deref;
750 if ("\t" eq "\011") { # ASCII
751 is("@cont", '23 5 fake foo');
753 else { # EBCDIC alpha-numeric sort order
754 is("@cont", 'fake foo 23 5');
756 my @keys = sort keys %$deref;
757 is("@keys", 'fake foo');
758 my @val = sort values %$deref;
760 is($deref->{foo}, 5);
761 is(defined $deref->{bar}, '');
764 push @keys, $key while $key = each %$deref;
766 is("@keys", 'fake foo');
767 is(exists $deref->{bar}, '');
768 is(exists $deref->{foo}, 1);
772 sub xxx_goto { goto &$deref }
774 my $srt = bless { c => sub {$b <=> $a}
777 my @sorted = sort srt 11, 2, 5, 1, 22;
778 is("@sorted", '22 11 5 2 1');
782 @sorted = sort $srt 11, 2, 5, 1, 22;
783 is("@sorted", '22 11 5 2 1');
785 is("@$deref", '11 12 13');
789 is($deref->[2], '13');
793 is($deref->[$l], '12');
794 # Repeated dereference
795 my $double = bless { h => $deref,
797 is($double->{foo}, 5);
802 use overload '%{}' => \&gethash, '@{}' => sub { ${shift()} };
810 tie %h, ref $self, $self;
814 sub TIEHASH { my $p = shift; bless \ shift, $p }
817 $fields{$_} = $i++ foreach qw{zero one two three};
819 my $self = ${shift()};
820 my $key = $fields{shift()};
821 defined $key or die "Out of band access";
822 $$self->[$key] = shift;
825 my $self = ${shift()};
826 my $key = $fields{shift()};
827 defined $key or die "Out of band access";
832 my $bar = new two_refs 3,4,5,6;
843 $bar = new two_refs_o 3,4,5,6;
851 use overload '%{}' => sub { ${shift()}->[1] },
852 '@{}' => sub { ${shift()}->[0] };
858 bless \ [$a, \%h], $p;
863 tie %h, ref $self, $self;
867 sub TIEHASH { my $p = shift; bless \ shift, $p }
870 $fields{$_} = $i++ foreach qw{zero one two three};
873 my $key = $fields{shift()};
874 defined $key or die "Out of band access";
879 my $key = $fields{shift()};
880 defined $key or die "Out of band access";
885 $bar = new two_refs_o 3,4,5,6;
893 @ISA = ('two_refs1');
896 $bar = new two_refs1_o 3,4,5,6;
904 use overload bool => sub { ${+shift} };
908 { my $bbbb = 0; $aaa = bless \$bbbb, B }
918 # check that overload isn't done twice by join
921 use overload '""' => sub { $c++ };
922 my $x = join '', bless([]), 'pq', bless([]);
926 # Test module-specific warning
928 # check the Odd number of arguments for overload::constant warning
930 local $SIG{__WARN__} = sub {$a = $_[0]} ;
931 $x = eval ' overload::constant "integer" ; ' ;
933 use warnings 'overload' ;
934 $x = eval ' overload::constant "integer" ; ' ;
935 like($a, qr/^Odd number of arguments for overload::constant at/);
939 # check the '$_[0]' is not an overloadable type warning
941 local $SIG{__WARN__} = sub {$a = $_[0]} ;
942 $x = eval ' overload::constant "fred" => sub {} ; ' ;
944 use warnings 'overload' ;
945 $x = eval ' overload::constant "fred" => sub {} ; ' ;
946 like($a, qr/^'fred' is not an overloadable type at/);
950 # check the '$_[1]' is not a code reference warning
952 local $SIG{__WARN__} = sub {$a = $_[0]} ;
953 $x = eval ' overload::constant "integer" => 1; ' ;
955 use warnings 'overload' ;
956 $x = eval ' overload::constant "integer" => 1; ' ;
957 like($a, qr/^'1' is not a code reference at/);
961 # check the invalid argument warning [perl #74098]
963 local $SIG{__WARN__} = sub {$a = $_[0]} ;
964 $x = eval ' use overload "~|_|~" => sub{} ' ;
965 eval ' no overload "~|_|~" ' ;
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');
972 eval ' no overload "~|_|~" ' ;
973 like($a, qr/^overload arg '~\|_\|~' is invalid at \(eval \d+\) line /,
974 'invalid arg warning');
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}
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}
992 use overload '""' => sub { 2+shift->[0] },
993 '0+' => sub { 9+shift->[0] };
994 sub new {my $p = shift; bless [shift], $p}
998 my $x = new noov_int 11;
1000 main::is("$int_x", 20);
1001 $x = new ov_int1 31;
1003 main::is("$int_x", 131);
1004 $x = new ov_int2 51;
1006 main::is("$int_x", 1054);
1009 # make sure that we don't infinitely recurse
1013 use overload '""' => sub { shift },
1014 '0+' => sub { shift },
1015 'bool' => sub { shift },
1018 # For some reason beyond me these have to be oks rather than likes.
1019 main::ok("$x" =~ /Recurse=ARRAY/);
1021 main::ok($x+0 =~ qr/Recurse=ARRAY/);
1024 # BugID 20010422.003
1028 'bool' => sub { return !$_[0]->is_zero() || undef; }
1034 return $self->{var} == 0;
1041 $self->{var} = shift;
1049 my $r = Foo->new(8);
1057 '""' => sub { return $_[0]->{var}; }
1064 $self->{var} = shift;
1071 my $utfvar = new utf8_o 200.2.1;
1072 is("$utfvar", 200.2.1); # 223 - stringify
1073 is("a$utfvar", "a".200.2.1); # 224 - overload via sv_2pv_flags
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.
1080 use overload '%{}' => sub { (caller(0))[0] eq 'Foo' ? $_[0] : die "zap" };
1082 @Foo::ISA = 'Hderef';
1083 sub new { bless {}, shift }
1084 sub xet { @_ == 2 ? $_[0]->{$_[1]} :
1085 @_ == 3 ? ($_[0]->{$_[1]} = $_[2]) : undef }
1089 is ($a->xet('b'), 42);
1090 ok (!defined eval { $a->{b} });
1095 use overload '=' => sub { 42 },
1096 '++' => sub { my $x = ${$_[0]}; $_[0] };
1097 sub new { my $x = 42; bless \$x }
1101 local $SIG{__WARN__} = sub { $warn++ };
1110 my ($int, $out1, $out2);
1112 BEGIN { $int = 0; overload::constant 'integer' => sub {$int++; 17}; }
1116 is($int, 2, "#24313"); # 230
1117 is($out1, 17, "#24313"); # 231
1118 is($out2, 17, "#24313"); # 232
1123 use overload cmp => sub { 0 };
1124 package perl31793_fb;
1125 use overload cmp => sub { 0 }, fallback => 1;
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]+\)$/);
1144 use overload (qw(0+ numify fallback 1));
1151 sub numify { ${$_[0]} }
1154 # These all check that overloaded values, rather than reference addresses,
1155 # are what are getting tested.
1156 my ($two, $one, $un, $deux) = map {new Numify $_} 2, 1, 1, 2;
1157 my ($ein, $zwei) = (1, 2);
1159 my %map = (one => 1, un => 1, ein => 1, deux => 2, two => 2, zwei => 2);
1160 foreach 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}";
1166 my $got = eval $ocode;
1168 my $expect = eval $rcode;
1170 is ($got, $expect, $ocode) or print "# $rcode\n";
1175 # check that overloading works in regexes
1179 '""' => sub { "^$_[0][0]\$" },
1183 ? (ref $_[1] ? $_[1][0] : $_[1]) . ':' .$_[0][0]
1184 : $_[0][0] . ':' . (ref $_[1] ? $_[1][0] : $_[1])
1189 my $a = bless [ "a" ], 'Foo493';
1191 like('x:a', qr/x$a/);
1192 like('x:a:=', qr/x$a=$/);
1193 like('x:a:a:=', qr/x$a$a=$/);
1200 use overload qr => sub { qr/x/ }, fallback => 1;
1203 my $x = bless [], "QRonly";
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("xx" =~ /x$x/, "qr-only matches with concat");
1210 like("$x", qr/^QRonly=ARRAY/, "qr-only doesn't have string overload");
1212 my $qr = bless qr/y/, "QRonly";
1213 ok("x" =~ $qr, "qr with qr-overload uses overload");
1214 ok("y" !~ $qr, "qr with qr-overload uses overload");
1215 is("$qr", "".qr/y/, "qr with qr-overload stringify");
1218 ok("y" =~ $rx, "bare rx with qr-overload doesn't overload match");
1219 ok("x" !~ $rx, "bare rx with qr-overload doesn't overload match");
1220 is("$rx", "".qr/y/, "bare rx with qr-overload stringify");
1224 use overload qr => sub { qr/x/ }, q/""/ => sub { "y" };
1227 my $x = bless [], "QRandSTR";
1228 ok("x" =~ $x, "qr+str uses qr for match");
1229 ok("y" !~ $x, "qr+str uses qr for match");
1230 ok("xx" =~ /x$x/, "qr+str uses qr for match with concat");
1231 is("$x", "y", "qr+str uses str for stringify");
1233 my $qr = bless qr/z/, "QRandSTR";
1234 is("$qr", "y", "qr with qr+str uses str for stringify");
1235 ok("xx" =~ /x$x/, "qr with qr+str uses qr for match");
1238 ok("z" =~ $rx, "bare rx with qr+str doesn't overload match");
1239 is("$rx", "".qr/z/, "bare rx with qr+str doesn't overload stringify");
1243 use overload qr => sub { $_[0]->(@_) };
1246 use overload qr => sub { $_[0] };
1249 my $rx = bless sub { ${ qr/x/ } }, "QRany";
1250 ok("x" =~ $rx, "qr overload accepts a bare rx");
1251 ok("y" !~ $rx, "qr overload accepts a bare rx");
1253 my $str = bless sub { "x" }, "QRany";
1254 ok(!eval { "x" =~ $str }, "qr overload doesn't accept a string");
1255 like($@, qr/^Overloaded qr did not return a REGEXP/, "correct error");
1257 my $oqr = bless qr/z/, "QRandSTR";
1258 my $oqro = bless sub { $oqr }, "QRany";
1259 ok("z" =~ $oqro, "qr overload doesn't recurse");
1261 my $qrs = bless qr/z/, "QRself";
1262 ok("z" =~ $qrs, "qr overload can return self");
1266 use overload q/""/ => sub { "x" };
1269 use overload q/""/ => sub { "x" }, fallback => 1;
1272 my $fb = bless [], "STRonlyFB";
1273 ok("x" =~ $fb, "qr falls back to \"\"");
1274 ok("y" !~ $fb, "qr falls back to \"\"");
1276 my $nofb = bless [], "STRonly";
1277 ok("x" =~ $nofb, "qr falls back even without fallback");
1278 ok("y" !~ $nofb, "qr falls back even without fallback");
1283 my $twenty_three = 23;
1284 # Check that constant overloading propagates into evals
1285 BEGIN { overload::constant integer => sub { 23 } }
1286 is(eval "17", $twenty_three);
1292 bool => sub { shift->is_cool };
1295 $_[0]->{name} eq 'cool';
1300 bless $_[0], 'Brap';
1304 sub delete_with_self {
1307 bless $self, 'Brap';
1318 $obj = bless {name => 'cool'}, 'Sklorsh';
1320 ok(eval {if ($obj) {1}; 1}, $@ || 'reblessed into nonexistent namespace');
1322 $obj = bless {name => 'cool'}, 'Sklorsh';
1323 $obj->delete_with_self;
1324 ok (eval {if ($obj) {1}; 1}, $@);
1326 my $a = $b = {name => 'hot'};
1327 bless $b, 'Sklorsh';
1328 is(ref $a, 'Sklorsh');
1329 is(ref $b, 'Sklorsh');
1330 ok(!$b, "Expect overloaded boolean");
1331 ok(!$a, "Expect overloaded boolean");
1337 bool => sub { shift->{truth} eq 'yes' },
1338 '0+' => sub { shift->{truth} eq 'yes' ? '1' : '0' },
1339 '!' => sub { shift->{truth} eq 'no' },
1342 sub new { my $class = shift; bless { truth => shift }, $class }
1346 my $yes = Flrbbbbb->new('yes');
1348 $x = 1 if $yes; is($x, 1);
1349 $x = 2 unless $yes; is($x, 1);
1350 $x = 3 if !$yes; is($x, 1);
1351 $x = 4 unless !$yes; is($x, 4);
1353 my $no = Flrbbbbb->new('no');
1355 $x = 1 if $no; is($x, 0);
1356 $x = 2 unless $no; is($x, 2);
1357 $x = 3 if !$no; is($x, 3);
1358 $x = 4 unless !$no; is($x, 3);
1361 $x = 1 if !$no && $yes; is($x, 1);
1362 $x = 2 unless !$no && $yes; is($x, 1);
1363 $x = 3 if $no || !$yes; is($x, 1);
1364 $x = 4 unless $no || !$yes; is($x, 4);
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);
1374 use Scalar::Util 'weaken';
1377 use overload '""' => sub {"CLiK KLAK"};
1384 $obj = bless do {my $a; \$a}, 'Shklitza';
1387 is ("$obj", "CLiK KLAK");
1388 is ("$ref", "CLiK KLAK");
1391 is ("$ref", "CLiK KLAK");
1393 bless $obj, 'Ksshfwoom';
1395 like ($obj, qr/^Ksshfwoom=/);
1396 like ($ref, qr/^Ksshfwoom=/);
1404 # bit operations have overloadable assignment variants too
1406 sub new { bless \$_[1], $_[0] }
1409 "&=" => sub { bit->new($_[0]->val . ' & ' . $_[1]->val) },
1410 "^=" => sub { bit->new($_[0]->val . ' ^ ' . $_[1]->val) },
1411 "|" => sub { bit->new($_[0]->val . ' | ' . $_[1]->val) }, # |= by fallback
1414 sub val { ${$_[0]} }
1418 my $a = bit->new(my $va = 'a');
1419 my $b = bit->new(my $vb = 'b');
1422 is($a->val, 'a & b', "overloaded &= works");
1424 my $c = bit->new(my $vc = 'c');
1427 is($b->val, 'b ^ c', "overloaded ^= works");
1429 my $d = bit->new(my $vd = 'd');
1432 is($c->val, 'c | d', "overloaded |= (by fallback) works");
1436 # comparison operators with nomethod (bug 41546)
1440 package nomethod_false;
1441 use overload nomethod => sub { $method = 'nomethod'; 0 };
1443 package nomethod_true;
1444 use overload nomethod => sub { $method= 'nomethod'; 'true' };
1448 local $SIG{__WARN__} = sub { $warning = $_[0] };
1450 my $f = bless [], 'nomethod_false';
1451 ($warning, $method) = ("", "");
1452 is($f eq 'whatever', 0, 'nomethod makes eq return 0');
1453 is($method, 'nomethod');
1455 my $t = bless [], 'nomethod_true';
1456 ($warning, $method) = ("", "");
1457 is($t eq 'whatever', 'true', 'nomethod makes eq return "true"');
1458 is($method, 'nomethod');
1459 is($warning, "", 'nomethod eq need not return number');
1462 package nomethod_false;
1463 use overload cmp => sub { $method = 'cmp'; 0 };
1465 $f = bless [], 'nomethod_false';
1466 ($warning, $method) = ("", "");
1467 ok($f eq 'whatever', 'eq falls back to cmp (nomethod not called)');
1471 package nomethod_true;
1472 use overload cmp => sub { $method = 'cmp'; 'true' };
1474 $t = bless [], 'nomethod_true';
1475 ($warning, $method) = ("", "");
1476 ok($t eq 'whatever', 'eq falls back to cmp (nomethod not called)');
1478 like($warning, qr/isn't numeric/, 'cmp should return number');
1483 # nomethod called for '!' after attempted fallback
1484 my $nomethod_called = 0;
1486 package nomethod_not;
1487 use overload nomethod => sub { $nomethod_called = 'yes'; };
1490 my $o = bless [], 'nomethod_not';
1493 is($nomethod_called, 'yes', "nomethod() is called for '!'");
1494 is($res, 'yes', "nomethod(..., '!') return value propagates");
1498 # Subtle bug pre 5.10, as a side effect of the overloading flag being
1499 # stored on the reference rather than the referent. Despite the fact that
1500 # objects can only be accessed via references (even internally), the
1501 # referent actually knows that it's blessed, not the references. So taking
1502 # a new, unrelated, reference to it gives an object. However, the
1503 # overloading-or-not flag was on the reference prior to 5.10, and taking
1504 # a new reference didn't (use to) copy it.
1508 use overload '""' => sub {${$_[0]}};
1511 return "$_[0], $_[1]";
1518 my $crunch_eth = bless \$string, $class;
1520 is("$crunch_eth", $string);
1521 is ($crunch_eth->Pie("Meat"), "$string, Meat");
1523 my $wham_eth = \$string;
1525 is("$wham_eth", $string,
1526 'This reference did not have overloading in 5.8.8 and earlier');
1527 is ($crunch_eth->Pie("Apple"), "$string, Apple");
1529 my $class = ref $wham_eth;
1532 # Bless it back into its own class!
1533 bless $wham_eth, $class;
1535 is("$wham_eth", $string);
1536 is ($crunch_eth->Pie("Blackbird"), "$string, Blackbird");
1541 use overload "0+" => sub { $_[0][0] += 1; 42 };
1542 package numify_self;
1543 use overload "0+" => sub { $_[0][0]++; $_[0] };
1544 package numify_other;
1545 use overload "0+" => sub { $_[0][0]++; $_[0][1] = bless [], 'numify_int' };
1546 package numify_by_fallback;
1547 use overload fallback => 1;
1550 my $o = bless [], 'numify_int';
1551 is(int($o), 42, 'numifies to integer');
1552 is($o->[0], 1, 'int() numifies only once');
1555 my $num_val = int($aref);
1556 my $r = bless $aref, 'numify_self';
1557 is(int($r), $num_val, 'numifies to self');
1558 is($r->[0], 1, 'int() numifies once when returning self');
1560 my $s = bless [], 'numify_other';
1561 is(int($s), 42, 'numifies to numification of other object');
1562 is($s->[0], 1, 'int() numifies once when returning other object');
1563 is($s->[1][0], 1, 'returned object numifies too');
1565 my $m = bless $aref, 'numify_by_fallback';
1566 is(int($m), $num_val, 'numifies to usual reference value');
1567 is(abs($m), $num_val, 'numifies to usual reference value');
1568 is(-$m, -$num_val, 'numifies to usual reference value');
1569 is(0+$m, $num_val, 'numifies to usual reference value');
1570 is($m+0, $num_val, 'numifies to usual reference value');
1571 is($m+$m, 2*$num_val, 'numifies to usual reference value');
1572 is(0-$m, -$num_val, 'numifies to usual reference value');
1573 is(1*$m, $num_val, 'numifies to usual reference value');
1574 is(int($m/1), $num_val, 'numifies to usual reference value');
1575 is($m%100, $num_val%100, 'numifies to usual reference value');
1576 is($m**1, $num_val, 'numifies to usual reference value');
1578 is(abs($aref), $num_val, 'abs() of ref');
1579 is(-$aref, -$num_val, 'negative of ref');
1580 is(0+$aref, $num_val, 'ref addition');
1581 is($aref+0, $num_val, 'ref addition');
1582 is($aref+$aref, 2*$num_val, 'ref addition');
1583 is(0-$aref, -$num_val, 'subtraction of ref');
1584 is(1*$aref, $num_val, 'multiplicaton of ref');
1585 is(int($aref/1), $num_val, 'division of ref');
1586 is($aref%100, $num_val%100, 'modulo of ref');
1587 is($aref**1, $num_val, 'exponentiation of ref');
1591 package CopyConstructorFallback;
1593 '++' => sub { "$_[0]"; $_[0] },
1595 sub new { bless {} => shift }
1599 my $o = CopyConstructorFallback->new;
1600 my $x = $o++; # would segfault
1602 is($x, $o, "copy constructor falls back to assignment (postinc)");
1603 is($y, $o, "copy constructor falls back to assignment (preinc)");
1606 # only scalar 'x' should currently overload
1614 'x' => sub { $x++; 1 },
1615 '0+' => sub { $n++; 1 },
1616 'nomethod' => sub { $nm++; 1 },
1627 ($x,$n,$nm) = (0,0,0);
1628 @a = ((1,2,$s) x $count);
1629 is("$x-$n-$nm", "0-0-0", 'repeat 1');
1631 ($x,$n,$nm) = (0,0,0);
1632 @a = ((1,$s,3) x $count);
1633 is("$x-$n-$nm", "0-0-0", 'repeat 2');
1635 ($x,$n,$nm) = (0,0,0);
1636 @a = ((1,2,3) x $s);
1637 is("$x-$n-$nm", "0-1-0", 'repeat 3');
1642 # RT #57012: magic items need to have mg_get() called before testing for
1643 # overload. Lack of this means that overloaded values returned by eg a
1644 # tied array didn't call overload methods.
1645 # We test here both a tied array and scalar, since the implementation of
1646 # tied arrays (and hashes) is such that in rvalue context, mg_get is
1647 # called prior to executing the op, while it isn't for a tied scalar.
1648 # We also check that return values are correctly tainted.
1649 # We try against two overload packages; one has all expected methods, the
1650 # other uses only fallback methods.
1654 # @tests holds a list of test cases. Each elem is an array ref with
1655 # the following entries:
1657 # * the value that the overload method should return
1659 # * the expression to be evaled. %s is replaced with the
1660 # variable being tested ($ta[0], $ts, or $plain)
1662 # * a string listing what functions we expect to be called.
1663 # Each method appends its name in parentheses, so "(=)(+)" means
1664 # we expect the copy constructor and then the add method to be
1667 # * like above, but what should be called for the fallback-only test
1668 # (in this case, nomethod() identifies itself as "(NM:*)" where *
1669 # is the op). If this value is undef, fallback tests are skipped.
1671 # * An array ref of expected counts of calls to FETCH/STORE.
1672 # The first three values are:
1673 # 1. the expected number of FETCHs for a tied array
1674 # 2. the expected number of FETCHs for a tied scalar
1675 # 3. the expected number of STOREs
1676 # If there are a further three elements present, then
1677 # these represent the expected counts for the fallback
1678 # version of the tests. If absent, they are assumed to
1679 # be the same as for the full method test
1681 # * Under the taint version of the tests, whether we expect
1682 # the result to be tainted (for example comparison ops
1683 # like '==' don't return a tainted value, even if their
1692 # A note on what methods to expect to be called, and
1693 # how many times FETCH/STORE is called:
1695 # Mutating ops (+=, ++ etc) trigger a copy ('='), since
1696 # the code can't distinguish between something that's been copied:
1697 # $a = foo->new(0); $b = $a; refcnt($$b) == 2
1698 # and overloaded objects stored in ties which will have extra
1699 # refcounts due to the tied_obj magic and entries on the tmps
1700 # stack when returning from FETCH etc. So we always copy.
1702 # This accounts for a '=', and an extra STORE.
1703 # We also have a FETCH returning the final value from the eval,
1704 # plus a FETCH in the overload subs themselves: ($_[0][0])
1705 # triggers one. However, tied aggregates have a mechanism to prevent
1706 # multiple fetches between STOREs, which means that the tied
1707 # hash skips doing a FETCH during '='.
1709 for (qw(+ - * / % ** << >> & | ^)) {
1711 $op = '%%' if $op eq '%';
1712 my $e = "%s $op= 3";
1714 # ARRAY FETCH: initial, sub+=, eval-return,
1715 # SCALAR FETCH: initial, sub=, sub+=, eval-return,
1716 # STORE: copy, mutator
1717 push @tests, [ 18, $e, "(=)($_=)", "(=)(NM:$_=)", [ 3, 4, 2 ], 1 ];
1720 "do { my \$arg = %s; \$_[2] ? (3 $op \$arg) : (\$arg $op 3) }";
1721 # ARRAY FETCH: initial
1722 # SCALAR FETCH: initial eval-return,
1723 push @tests, [ 18, "%s $op 3", "($_)", "(NM:$_)", [ 1, 2, 0 ], 1 ];
1724 push @tests, [ 18, "3 $op %s", "($_)", "(NM:$_)", [ 1, 2, 0 ], 1 ];
1727 # these use string fallback rather than nomethod
1730 my $e = "%s $op= 3";
1733 # ARRAY FETCH: initial, sub+=, eval-return,
1734 # SCALAR FETCH: initial, sub=, sub+=, eval-return,
1735 # STORE: copy, mutator
1736 # for fallback, we just stringify, so eval-return and copy skipped
1738 push @tests, [ 18, $e, "(=)($_=)", '("")',
1739 [ 3, 4, 2, 2, 3, 1 ], 1 ];
1742 "do { my \$arg = %s; \$_[2] ? (3 $op \$arg) : (\$arg $op 3) }";
1743 # ARRAY FETCH: initial
1744 # SCALAR FETCH: initial eval-return,
1745 # with fallback, we just stringify, so eval-return skipped,
1746 # but an extra FETCH happens in sub"", except for 'x',
1747 # which passes a copy of the RV to sub"", avoiding the
1750 push @tests, [ 18, "%s $op 3", "($_)", '("")',
1751 [ 1, 2, 0, 1, ($_ eq '.' ? 2 : 1), 0 ], 1 ];
1752 next if $_ eq 'x'; # repeat only overloads on LHS
1753 push @tests, [ 18, "3 $op %s", "($_)", '("")',
1754 [ 1, 2, 0, 1, 2, 0 ], 1 ];
1762 # ARRAY FETCH: initial, sub+=, eval-return,
1763 # SCALAR FETCH: initial, sub=, sub+=, eval-return,
1764 # STORE: copy, mutator
1765 [ 18, $pre, "(=)($_)(\"\")", "(=)(NM:$_)(\"\")", [ 3, 4, 2 ], 1 ],
1766 # ARRAY FETCH: initial, sub+=
1767 # SCALAR FETCH: initial, sub=, sub+=
1768 # STORE: copy, mutator
1769 [ 18, $post, "(=)($_)(\"\")", "(=)(NM:$_)(\"\")", [ 2, 3, 2 ], 1 ];
1772 # For the non-mutator ops, we have a initial FETCH,
1773 # an extra FETCH within the sub itself for the scalar option,
1776 for (qw(< <= > >= == != lt le gt ge eq ne)) {
1779 push @tests, [ 3, $e, "($_)", "(NM:$_)", [ 1, 2, 0 ], 0 ];
1784 push @tests, [ 3, $e, "($_)", "(NM:$_)", [ 1, 2, 0 ], 1 ];
1789 push @tests, [ 18, $e, "($_)", "(NM:$_)", [ 1, 2, 0 ], 1 ];
1791 for (qw(cos sin exp abs log sqrt int ~)) {
1794 push @tests, [ 1.23, $e, "($_)",
1795 ($_ eq 'int' ? '(0+)' : "(NM:$_)") , [ 1, 2, 0 ], 1 ];
1800 push @tests, [ 1.23, $e, "($_)", '(0+)', [ 1, 2, 0 ], 0 ];
1805 push @tests, [ 18, $e, '(neg)', '(NM:neg)', [ 1, 2, 0 ], 1 ];
1807 my $e = '(%s) ? 1 : 0';
1809 push @tests, [ 18, $e, '(bool)', '(0+)', [ 1, 2, 0 ], 0 ];
1811 # note: this is testing unary qr, not binary =~
1812 $subs{qr} = '(qr/%s/)';
1813 push @tests, [ "abc", '"abc" =~ (%s)', '(qr)', '("")', [ 1, 2, 0 ], 0 ];
1814 push @tests, [ chr 256, 'chr(256) =~ (%s)', '(qr)', '("")',
1817 $e = '"abc" ~~ (%s)';
1819 push @tests, [ "abc", $e, '(~~)', '(NM:~~)', [ 1, 1, 0 ], 0 ];
1821 $subs{'-X'} = 'do { my $f = (%s);'
1822 . '$_[1] eq "r" ? (-r ($f)) :'
1823 . '$_[1] eq "e" ? (-e ($f)) :'
1824 . '$_[1] eq "f" ? (-f ($f)) :'
1825 . '$_[1] eq "l" ? (-l ($f)) :'
1826 . '$_[1] eq "t" ? (-t ($f)) :'
1827 . '$_[1] eq "T" ? (-T ($f)) : 0;}';
1828 # Note - we don't care what these file tests return, as
1829 # long as the tied and untied versions return the same value.
1830 # The flags below are chosen to test all uses of tryAMAGICftest_MG
1831 for (qw(r e f l t T)) {
1832 push @tests, [ 'TEST', "-$_ (%s)", '(-X)', '("")', [ 1, 2, 0 ], 0 ];
1835 $subs{'${}'} = '%s';
1836 push @tests, [ do {my $s=99; \$s}, '${%s}', '(${})', undef, [ 1, 1, 0 ], 0 ];
1838 # we skip testing '@{}' here because too much of this test
1839 # framework involves array dereferences!
1841 $subs{'%{}'} = '%s';
1842 push @tests, [ {qw(a 1 b 2 c 3)}, 'join "", sort keys %%{%s}',
1843 '(%{})', undef, [ 1, 1, 0 ], 0 ];
1845 $subs{'&{}'} = '%s';
1846 push @tests, [ sub {99}, 'do {&{%s} for 1,2}',
1847 '(&{})(&{})', undef, [ 2, 2, 0 ], 0 ];
1851 $subs{'*{}'} = '%s';
1852 push @tests, [ \*RT57012A, '*RT57012B = *{%s}; our $RT57012B',
1853 '(*{})', undef, [ 1, 1, 0 ], 0 ];
1855 my $iter_text = ("some random text\n" x 100) . $^X;
1856 open my $iter_fh, '<', \$iter_text
1857 or die "open of \$iter_text gave ($!)\n";
1858 $subs{'<>'} = '<$iter_fh>';
1859 push @tests, [ $iter_fh, '<%s>', '(<>)', undef, [ 1, 1, 0 ], 1 ];
1860 push @tests, [ $iter_fh,
1861 'local *CORE::GLOBAL::glob = sub {}; eval q|<%s>|',
1862 '(<>)', undef, [ 1, 1, 0 ], 1 ];
1864 # eval should do tie, overload on its arg before checking taint */
1865 push @tests, [ '1;', 'eval q(eval %s); $@ =~ /Insecure/',
1866 '("")', '("")', [ 1, 2, 0 ], 0 ];
1869 for my $sub (keys %subs) {
1870 my $term = $subs{$sub};
1871 my $t = sprintf $term, '$_[0][0]';
1872 my $e ="sub { \$funcs .= '($sub)'; my \$r; if (\$use_int) {"
1873 . "use integer; \$r = ($t) } else { \$r = ($t) } \$r }";
1874 $subs{$sub} = eval $e;
1875 die "Compiling sub gave error:\n<$e>\n<$@>\n" if $@;
1886 "=" => sub { $funcs .= '(=)'; bless [ $_[0][0] ] },
1887 '0+' => sub { $funcs .= '(0+)'; 0 + $_[0][0] },
1888 '""' => sub { $funcs .= '("")'; "$_[0][0]" },
1891 package RT57012_OV_FB; # only contains fallback conversion functions
1894 "=" => sub { $funcs .= '(=)'; bless [ $_[0][0] ] },
1895 '0+' => sub { $funcs .= '(0+)'; 0 + $_[0][0] },
1896 '""' => sub { $funcs .= '("")'; "$_[0][0]" },
1898 $funcs .= "(NM:$_[3])";
1899 my $e = defined($_[1])
1902 ? "atan2(\$_[1],\$_[0][0])"
1903 : "atan2(\$_[0][0],\$_[1])"
1905 ? "\$_[1] $_[3] \$_[0][0]"
1906 : "\$_[0][0] $_[3] \$_[1]"
1909 : "$_[3](\$_[0][0])";
1912 use integer; $r = eval $e;
1917 ::diag("eval of nomethod <$e> gave <$@>") if $@;
1923 package RT57012_TIE_S;
1926 sub TIESCALAR { bless [ bless [ $tie_val ], $_[1] ] }
1927 sub FETCH { $fetches++; $_[0][0] }
1928 sub STORE { $stores++; $_[0][0] = $_[1] }
1930 package RT57012_TIE_A;
1932 sub TIEARRAY { bless [] }
1933 sub FETCH { $fetches++; $_[0][0] }
1934 sub STORE { $stores++; $_[0][$_[1]] = $_[2] }
1938 for my $test (@tests) {
1939 my ($val, $sub_term, $exp_funcs, $exp_fb_funcs,
1940 $exp_counts, $exp_taint) = @$test;
1944 # create tainted version of $val (unless its a ref)
1945 my $t = substr($^X,0,0);
1947 my $val1 = $val; # use a copy to avoid stringifying original
1948 $tainted_val = ref($val1) ? $val :
1949 ($val1 =~ /^[\d\.]+$/) ? $val+$t0 : $val.$t;
1951 $tie_val = $tainted_val;
1953 for my $int ('', 'use integer; ') {
1954 $use_int = ($int ne '');
1955 my $plain = $tainted_val;
1956 my $plain_term = $int . sprintf $sub_term, '$plain';
1957 my $exp = eval $plain_term;
1958 diag("eval of plain_term <$plain_term> gave <$@>") if $@;
1959 is(tainted($exp), $exp_taint,
1960 "<$plain_term> taint of expected return");
1962 for my $ov_pkg (qw(RT57012_OV RT57012_OV_FB)) {
1963 next if $ov_pkg eq 'RT57012_OV_FB'
1964 and not defined $exp_fb_funcs;
1965 my ($exp_fetch_a, $exp_fetch_s, $exp_store) =
1966 ($ov_pkg eq 'RT57012_OV' || @$exp_counts < 4)
1967 ? @$exp_counts[0,1,2]
1968 : @$exp_counts[3,4,5];
1970 tie my $ts, 'RT57012_TIE_S', $ov_pkg;
1971 tie my @ta, 'RT57012_TIE_A';
1972 $ta[0] = bless [ $tainted_val ], $ov_pkg;
1973 my $oload = bless [ $tainted_val ], $ov_pkg;
1975 for my $var ('$ta[0]', '$ts', '$oload',
1976 ($sub_term eq '<%s>' ? '${ts}' : ())
1983 my $res_term = $int . sprintf $sub_term, $var;
1984 my $desc = "<$res_term> $ov_pkg" ;
1985 my $res = eval $res_term;
1986 diag("eval of res_term $desc gave <$@>") if $@;
1987 # uniquely, the inc/dec ops return the original
1988 # ref rather than a copy, so stringify it to
1989 # find out if its tainted
1990 $res = "$res" if $res_term =~ /\+\+|--/;
1991 is(tainted($res), $exp_taint,
1992 "$desc taint of result return");
1993 is($res, $exp, "$desc return value");
1994 my $fns =($ov_pkg eq 'RT57012_OV_FB')
1995 ? $exp_fb_funcs : $exp_funcs;
1996 if ($var eq '$oload' && $res_term !~ /oload(\+\+|--)/) {
1997 # non-tied overloading doesn't trigger a copy
1998 # except for post inc/dec
2001 is($funcs, $fns, "$desc methods called");
2002 next if $var eq '$oload';
2003 my $exp_fetch = ($var eq '$ts') ?
2004 $exp_fetch_s : $exp_fetch_a;
2005 is($fetches, $exp_fetch, "$desc FETCH count");
2006 is($stores, $exp_store, "$desc STORE count");
2015 # Test overload from the main package
2017 '$^W = 1; use overload q\""\ => sub {"ning"}; print bless []',
2019 { switches => ['-wl'], stderr => 1 },
2020 'use overload from the main package'
2024 package blessed_methods;
2025 use overload '+' => sub {};
2026 bless overload::Method __PACKAGE__,'+';
2027 eval { overload::Method __PACKAGE__,'+' };
2028 ::is($@, '', 'overload::Method and blessed overload methods');
2032 # fallback to 'cmp' and '<=>' with heterogeneous operands
2034 my $not_found = 'no method found';
2039 bless \$n, ref $_[0] || $_[0];
2043 (${$_[0]} <=> ${$_[1]}) * ($_[2] ? -1 : 1);
2048 use overload '<=>' => 'cmp';
2052 use overload 'cmp' => 'cmp';
2055 my $n = NCmp->new(5);
2056 my $s = SCmp->new(3);
2059 eval { $res = $n > $s; };
2060 $res = $not_found if $@ =~ /$not_found/;
2061 is($res, 1, 'A>B using A<=> when B overloaded, no B<=>');
2063 eval { $res = $s < $n; };
2064 $res = $not_found if $@ =~ /$not_found/;
2065 is($res, 1, 'A<B using B<=> when A overloaded, no A<=>');
2067 eval { $res = $s lt $n; };
2068 $res = $not_found if $@ =~ /$not_found/;
2069 is($res, 1, 'A lt B using A:cmp when B overloaded, no B:cmp');
2071 eval { $res = $n gt $s; };
2072 $res = $not_found if $@ =~ /$not_found/;
2073 is($res, 1, 'A gt B using B:cmp when A overloaded, no A:cmp');
2075 my $o = NCmp->new(9);
2077 is($used, \$n, 'A < B uses <=> from A in preference to B');
2079 my $t = SCmp->new(7);
2081 is($used, \$s, 'A lt B uses cmp from A in preference to B');
2085 # Combinatorial testing of 'fallback' and 'nomethod'
2088 use overload '0+' => sub { ${$_[0]}; },
2092 my $n = @_ ? shift : 0;
2093 bless my $obj = \$n, ref $self || $self;
2097 my $s = "(${$_[0]} ";
2098 $s .= "nomethod, " if defined ${ref($_[0]).'::(nomethod'};
2099 my $fb = ${ref($_[0]).'::()'};
2100 $s .= "fb=" . (defined $fb ? 0 + $fb : 'undef') . ")";
2102 sub nomethod { "${$_[0]}.nomethod"; }
2104 # create classes for tests
2106 my @falls = (0, 'undef', 1);
2107 my @nomethods = ('', 'nomethod');
2108 my $not_found = 'no method found';
2109 for my $fall (@falls) {
2110 for my $nomethod (@nomethods) {
2111 my $nomethod_decl = $nomethod
2112 ? $nomethod . "=>'nomethod'," : '';
2114 package NuMB$fall$nomethod;
2116 use overload $nomethod_decl
2122 # operation and precedence of 'fallback' and 'nomethod'
2123 # for all combinations with 2 overloaded operands
2124 for my $nomethod2 (@nomethods) {
2125 for my $nomethod1 (@nomethods) {
2126 for my $fall2 (@falls) {
2127 my $pack2 = "NuMB$fall2$nomethod2";
2128 for my $fall1 (@falls) {
2129 my $pack1 = "NuMB$fall1$nomethod1";
2130 my ($test, $out, $exp);
2132 my \$x = $pack1->new(2);
2133 my \$y = $pack2->new(3);
2134 \$test = "\$x" . ' * ' . "\$y";
2137 $out = $not_found if $@ =~ /$not_found/;
2138 $exp = $nomethod1 ? '2.nomethod' :
2139 $nomethod2 ? '3.nomethod' :
2140 $fall1 eq '1' && $fall2 eq '1' ? 6
2142 is($out, $exp, "$test --> $exp");
2148 # operation of 'fallback' and 'nomethod'
2149 # where the other operand is not overloaded
2150 for my $nomethod (@nomethods) {
2151 for my $fall (@falls) {
2152 my ($test, $out, $exp);
2154 my \$x = NuMB$fall$nomethod->new(2);
2155 \$test = "\$x" . ' * 3';
2158 $out = $not_found if $@ =~ /$not_found/;
2159 $exp = $nomethod ? '2.nomethod' :
2162 is($out, $exp, "$test --> $exp");
2165 my \$x = NuMB$fall$nomethod->new(2);
2166 \$test = '3 * ' . "\$x";
2169 $out = $not_found if $@ =~ /$not_found/;
2170 is($out, $exp, "$test --> $exp");
2175 # since 5.6 overloaded <> was leaving an extra arg on the stack!
2179 use overload '<>' => sub { 11 };
2181 my $a = bless [], 'Iter1';
2183 my @a = (10, ($x = <$a>), 12);
2184 is ($a[0], 10, 'Iter1: a[0]');
2185 is ($a[1], 11, 'Iter1: a[1]');
2186 is ($a[2], 12, 'Iter1: a[2]');
2187 @a = (10, ($x .= <$a>), 12);
2188 is ($a[0], 10, 'Iter1: a[0] concat');
2189 is ($a[1], 1111, 'Iter1: a[1] concat');
2190 is ($a[2], 12, 'Iter1: a[2] concat');
2193 # Some tests for error messages
2196 use overload '+' => 'justice';
2198 ::like $@, qr/^Can't resolve method "justice" overloading "\+" in p(?x:
2199 )ackage "Justus" at /,
2200 'Error message when explicitly named overload method does not exist';
2203 our @ISA = 'JustYou';
2204 package JustYou { use overload '+' => 'injustice'; }
2207 ::like $@, qr/^Stub found while resolving method "\?{3}" overloadin(?x:
2208 )g "\+" in package "JustUs" at /,
2209 'Error message when sub stub is encountered';
2213 # overload::Overloaded should not use a ->can designed for autoloading.
2214 # This example attempts to be as realistic as possible. The o class has a
2215 # default singleton object, but can have instances, too. The proxy class
2216 # represents proxies for o objects, but class methods delegate to the
2218 # overload::Overloaded used to return incorrect results for proxy objects.
2220 sub new { bless [$_[1]], $_[0] }
2222 our $AUTOLOAD =~ s/.*:://;
2225 sub can { SUPER::can{@_} || &_self->can($_[1]) }
2226 sub _self { ref $_[0] ? $_[0][0] : $o::singleton }
2228 package o { use overload '""' => sub { 'keck' };
2229 sub new { bless[], $_[0] }
2230 our $singleton = o->new; }
2231 ok !overload::Overloaded(new proxy new o),
2232 'overload::Overloaded does not incorrectly return true for proxy classes';
2234 # Another test, based on the type of explosive test class for which
2235 # perl #40333 was filed.
2239 use overload '""' => sub {"Ahoy!"};
2242 my $obj = bless [], 'broken_can';
2243 ok(overload::Overloaded($obj));
2246 sub eleventative::cos { 'eleven' }
2247 sub twelvetative::abs { 'twelve' }
2248 sub thirteentative::abs { 'thirteen' }
2249 sub fourteentative::abs { 'fourteen' }
2250 @eleventative::ISA = twelvetative::;
2252 my $o = bless [], 'eleventative';
2253 eval 'package eleventative; use overload map +($_)x2, cos=>abs=>';
2254 is cos $o, 'eleven', 'overloading applies to object blessed before';
2255 bless [], 'eleventative';
2256 is cos $o, 'eleven',
2257 'ovrld applies to previously-blessed obj after other obj is blessed';
2258 $o = bless [], 'eleventative';
2259 *eleventative::cos = sub { 'ten' };
2260 is cos $o, 'ten', 'method changes affect overloading';
2261 @eleventative::ISA = thirteentative::;
2262 is abs $o, 'thirteen', 'isa changes affect overloading';
2263 bless $o, 'fourteentative';
2264 @fourteentative::ISA = 'eleventative';
2265 is abs $o, 'fourteen', 'isa changes can turn overloading on';
2268 # no overload "fallback";
2270 use overload fallback => 1, '""' => sub { 'arakas' };
2271 no overload 'fallback';
2273 $a = bless [], 'phake';
2275 'no overload "fallback" does not stop overload from working';
2276 ok !eval { () = $a eq 'mpizeli'; 1 },
2277 'no overload "fallback" resets fallback to undef on overloaded class';
2278 { package ent; use overload fallback => 0, abs => sub{};
2281 use overload fallback => 1;
2283 no overload "fallback"; # disable previous declaration
2285 $a = bless [], ent::;
2286 is eval {"$a"}, overload::StrVal($a),
2287 'no overload undoes fallback declaration completetly'
2290 # inherited fallback
2293 our @ISA = 'vtoryy';
2294 use overload "abs" =>=> sub {};
2296 use overload fallback => 1, 'sin' =>=> sub{}
2298 $a = bless [], pervyy::;
2299 is eval {"$a"}, overload::StrVal($a),
2300 'fallback is inherited by classes that have their own overloading'
2303 # package separators in method names
2306 use overload q\""\ => "bear::strength";
2307 use overload bool => "bear'bouillon";
2309 @bear::ISA = 'food';
2310 sub food::strength { 'twine' }
2311 sub food::bouillon { 0 }
2312 $a = bless[], mane::;
2313 is eval { "$a" }, 'twine', ':: in method name' or diag $@;
2314 is eval { !$a }, 1, "' in method name" or diag $@;
2317 { # undefining the overload stash -- KEEP THIS TEST LAST
2319 use overload '+' => 'onion';
2320 $_ = \&overload::nil;
2323 ::ok(1, 'no crash when undefining %overload::');