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 blessing to a package updates hash
272 eval "package Oscalar; no overload '.'";
274 is("b${a}", "_.b.__.xx._");
277 is("b${a}c", "bxxc");
279 is("b${a}c", "bxxc");
281 # Negative overloading:
284 like($@, qr/no method found/);
289 sub { *{"Oscalar::$AUTOLOAD"} = sub {"_!_" . shift() . "_!_"} ;
290 goto &{"Oscalar::$AUTOLOAD"}};
292 eval "package Oscalar; sub comple; use overload '~' => 'comple'";
294 $na = eval { ~$a }; # Hash was not updated
295 like($@, qr/no method found/);
299 $na = eval { ~$a }; # Hash updated
300 warn "`$na', $@" if $@;
306 $na = eval { ~$aI }; # Hash was not updated
307 like($@, qr/no method found/);
317 eval "package Oscalar; sub rshft; use overload '>>' => 'rshft'";
319 $na = eval { $aI >> 1 }; # Hash was not updated
320 like($@, qr/no method found/);
326 $na = eval { $aI >> 1 };
332 # warn overload::Method($a, '0+'), "\n";
333 is(overload::Method($a, '0+'), \&Oscalar::numify);
334 is(overload::Method($aI,'0+'), \&Oscalar::numify);
335 ok(overload::Overloaded($aI));
336 ok(!overload::Overloaded('overload'));
338 ok(! defined overload::Method($aI, '<<'));
339 ok(! defined overload::Method($a, '<'));
341 like (overload::StrVal($aI), qr/^OscalarI=SCALAR\(0x[\da-fA-F]+\)$/);
342 is(overload::StrVal(\$aI), "@{[\$aI]}");
344 # Check overloading by methods (specified deep in the ISA tree).
348 sub Oscalar::lshft {"_<<_" . shift() . "_<<_"}
349 eval "package OscalarI; use overload '<<' => 'lshft', '|' => 'lshft'";
354 bless $aII, 'OscalarII';
355 bless \$fake, 'OscalarI'; # update the hash
356 is(($aI | 3), '_<<_xx_<<_');
358 is(($aII << 3), '_<<_087_<<_');
361 BEGIN { $int = 7; overload::constant 'integer' => sub {$int++; shift}; }
368 BEGIN { overload::constant 'integer' => sub {$int++; shift()+1}; }
377 BEGIN { $q = $qr = 7;
378 overload::constant 'q' => sub {$q++; push @q, shift, ($_[1] || 'none'); shift},
379 'qr' => sub {$qr++; push @qr, shift, ($_[1] || 'none'); shift}; }
382 $out2 = "a\a$foo,\,";
388 is($out1, 'f\'o\\o');
390 is($out2, "a\afoo,\,");
391 is("@q", "foo q f'o\\\\o q a\\a qq ,\\, qq");
393 is("@qr", "b\\b qq .\\. qq");
397 $_ = '!<b>!foo!<-.>!';
398 BEGIN { overload::constant 'q' => sub {push @q1, shift, ($_[1] || 'none'); "_<" . (shift) . ">_"},
399 'qr' => sub {push @qr1, shift, ($_[1] || 'none'); "!<" . (shift) . ">!"}; }
402 $out2 = "a\a$foo,\,";
412 s'first part'second part';
413 s/yet another/tail here/;
418 is($out1, '_<f\'o\\o>_');
419 is($out2, "_<a\a>_foo_<,\,>_");
420 is("@q1", "foo q f'o\\\\o q a\\a qq ,\\, qq oups
422 q second part q tail here s A-Z tr a-z tr");
423 is("@qr1", "b\\b qq .\\. qq try it q first part q yet another qq");
432 package symbolic; # Primitive symbolic calculator
433 use overload nomethod => \&wrap, '""' => \&str, '0+' => \&num,
434 '=' => \&cpy, '++' => \&inc, '--' => \&dec;
436 sub new { shift; bless ['n', @_] }
439 bless [@$self], ref $self;
441 sub inc { $_[0] = bless ['++', $_[0], 1]; }
442 sub dec { $_[0] = bless ['--', $_[0], 1]; }
444 my ($obj, $other, $inv, $meth) = @_;
445 if ($meth eq '++' or $meth eq '--') {
446 @$obj = ($meth, (bless [@$obj]), 1); # Avoid circular reference
449 ($obj, $other) = ($other, $obj) if $inv;
450 bless [$meth, $obj, $other];
453 my ($meth, $a, $b) = @{+shift};
454 $a = 'u' unless defined $a;
461 my %subr = ( 'n' => sub {$_[0]} );
462 foreach my $op (split " ", $overload::ops{with_assign}) {
463 $subr{$op} = $subr{"$op="} = eval "sub {shift() $op shift()}";
465 my @bins = qw(binary 3way_comparison num_comparison str_comparison);
466 foreach my $op (split " ", "@overload::ops{ @bins }") {
467 $subr{$op} = eval "sub {shift() $op shift()}";
469 foreach my $op (split " ", "@overload::ops{qw(unary func)}") {
470 $subr{$op} = eval "sub {$op shift()}";
472 $subr{'++'} = $subr{'+'};
473 $subr{'--'} = $subr{'-'};
476 my ($meth, $a, $b) = @{+shift};
477 my $subr = $subr{$meth}
478 or die "Do not know how to ($meth) in symbolic";
479 $a = $a->num if ref $a eq __PACKAGE__;
480 $b = $b->num if ref $b eq __PACKAGE__;
483 sub TIESCALAR { my $pack = shift; $pack->new(@_) }
485 sub nop { } # Around a bug
486 sub vars { my $p = shift; tie($_, $p), $_->nop foreach @_; }
495 my $foo = new symbolic 11;
497 is((sprintf "%d", $foo), '12');
498 is((sprintf "%d", $baz), '11');
501 is((sprintf "%d", $foo), '13');
502 is((sprintf "%d", $bar), '12');
503 is((sprintf "%d", $baz), '13');
506 is((sprintf "%d", $foo), '14');
507 is((sprintf "%d", $bar), '12');
508 is((sprintf "%d", $baz), '14');
509 is((sprintf "%d", $ban), '13');
512 is((sprintf "%d", $foo), '15');
513 is((sprintf "%d", $baz), '14');
514 is("$foo", '[++ [+= [++ [++ [n 11] 1] 1] 1] 1]');
518 my $iter = new symbolic 2;
519 my $side = new symbolic 1;
523 $cnt = $cnt - 1; # The "simple" way
524 $side = (sqrt(1 + $side**2) - 1)/$side;
526 my $pi = $side*(2**($iter+2));
527 is("$side", '[/ [- [sqrt [+ 1 [** [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1] [n 1]] 2]]] 1] [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1] [n 1]]]');
528 is((sprintf "%f", $pi), '3.182598');
532 my $iter = new symbolic 2;
533 my $side = new symbolic 1;
537 $side = (sqrt(1 + $side**2) - 1)/$side;
539 my $pi = $side*(2**($iter+2));
540 is("$side", '[/ [- [sqrt [+ 1 [** [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1] [n 1]] 2]]] 1] [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1] [n 1]]]');
541 is((sprintf "%f", $pi), '3.182598');
546 symbolic->vars($a, $b);
547 my $c = sqrt($a**2 + $b**2);
549 is((sprintf "%d", $c), '5');
551 is((sprintf "%d", $c), '13');
555 package symbolic1; # Primitive symbolic calculator
557 use overload nomethod => \&wrap, '""' => \&str, '0+' => \&num, '=' => \&cpy;
559 sub new { shift; bless ['n', @_] }
562 bless [@$self], ref $self;
565 my ($obj, $other, $inv, $meth) = @_;
566 if ($meth eq '++' or $meth eq '--') {
567 @$obj = ($meth, (bless [@$obj]), 1); # Avoid circular reference
570 ($obj, $other) = ($other, $obj) if $inv;
571 bless [$meth, $obj, $other];
574 my ($meth, $a, $b) = @{+shift};
575 $a = 'u' unless defined $a;
582 my %subr = ( 'n' => sub {$_[0]} );
583 foreach my $op (split " ", $overload::ops{with_assign}) {
584 $subr{$op} = $subr{"$op="} = eval "sub {shift() $op shift()}";
586 my @bins = qw(binary 3way_comparison num_comparison str_comparison);
587 foreach my $op (split " ", "@overload::ops{ @bins }") {
588 $subr{$op} = eval "sub {shift() $op shift()}";
590 foreach my $op (split " ", "@overload::ops{qw(unary func)}") {
591 $subr{$op} = eval "sub {$op shift()}";
593 $subr{'++'} = $subr{'+'};
594 $subr{'--'} = $subr{'-'};
597 my ($meth, $a, $b) = @{+shift};
598 my $subr = $subr{$meth}
599 or die "Do not know how to ($meth) in symbolic";
600 $a = $a->num if ref $a eq __PACKAGE__;
601 $b = $b->num if ref $b eq __PACKAGE__;
604 sub TIESCALAR { my $pack = shift; $pack->new(@_) }
606 sub vars { my $p = shift; tie($_, $p) foreach @_; }
615 my $foo = new symbolic1 11;
617 is((sprintf "%d", $foo), '12');
618 is((sprintf "%d", $baz), '11');
621 is((sprintf "%d", $foo), '13');
622 is((sprintf "%d", $bar), '12');
623 is((sprintf "%d", $baz), '13');
626 is((sprintf "%d", $foo), '14');
627 is((sprintf "%d", $bar), '12');
628 is((sprintf "%d", $baz), '14');
629 is((sprintf "%d", $ban), '13');
632 is((sprintf "%d", $foo), '15');
633 is((sprintf "%d", $baz), '14');
634 is("$foo", '[++ [+= [++ [++ [n 11] 1] 1] 1] 1]');
638 my $iter = new symbolic1 2;
639 my $side = new symbolic1 1;
643 $cnt = $cnt - 1; # The "simple" way
644 $side = (sqrt(1 + $side**2) - 1)/$side;
646 my $pi = $side*(2**($iter+2));
647 is("$side", '[/ [- [sqrt [+ 1 [** [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1] [n 1]] 2]]] 1] [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1] [n 1]]]');
648 is((sprintf "%f", $pi), '3.182598');
652 my $iter = new symbolic1 2;
653 my $side = new symbolic1 1;
657 $side = (sqrt(1 + $side**2) - 1)/$side;
659 my $pi = $side*(2**($iter+2));
660 is("$side", '[/ [- [sqrt [+ 1 [** [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1] [n 1]] 2]]] 1] [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1] [n 1]]]');
661 is((sprintf "%f", $pi), '3.182598');
666 symbolic1->vars($a, $b);
667 my $c = sqrt($a**2 + $b**2);
669 is((sprintf "%d", $c), '5');
671 is((sprintf "%d", $c), '13');
675 package two_face; # Scalars with separate string and
677 sub new { my $p = shift; bless [@_], $p }
678 use overload '""' => \&str, '0+' => \&num, fallback => 1;
684 my $seven = new two_face ("vii", 7);
685 is((sprintf "seven=$seven, seven=%d, eight=%d", $seven, $seven+1),
686 'seven=vii, seven=7, eight=8');
687 is(scalar ($seven =~ /i/), '1');
692 use overload 'cmp' => \∁
693 sub new { my ($p, $v) = @_; bless \$v, $p }
694 sub comp { my ($x,$y) = @_; ($$x * 3 % 10) <=> ($$y * 3 % 10) or $$x cmp $$y }
697 my @arr = map sorting->new($_), 0..12;
698 my @sorted1 = sort @arr;
699 my @sorted2 = map $$_, @sorted1;
700 is("@sorted2", '0 10 7 4 1 11 8 5 12 2 9 6 3');
704 use overload '<>' => \&iter;
705 sub new { my ($p, $v) = @_; bless \$v, $p }
706 sub iter { my ($x) = @_; return undef if $$x < 0; return $$x--; }
710 my $iter = iterator->new(5);
713 $acc .= " $out" while $out = <${iter}>;
714 is($acc, ' 5 4 3 2 1 0');
715 $iter = iterator->new(5);
716 is(scalar <${iter}>, '5');
718 $acc .= " $out" while $out = <$iter>;
719 is($acc, ' 4 3 2 1 0');
723 use overload '%{}' => \&hderef, '&{}' => \&cderef,
724 '*{}' => \&gderef, '${}' => \&sderef, '@{}' => \&aderef;
725 sub new { my ($p, $v) = @_; bless \$v, $p }
727 my ($self, $key) = (shift, shift);
728 my $class = ref $self;
729 bless $self, 'deref::dummy'; # Disable overloading of %{}
730 my $out = $self->{$key};
731 bless $self, $class; # Restore overloading
734 sub hderef {shift->deref('h')}
735 sub aderef {shift->deref('a')}
736 sub cderef {shift->deref('c')}
737 sub gderef {shift->deref('g')}
738 sub sderef {shift->deref('s')}
741 my $deref = bless { h => { foo => 5 , fake => 23 },
742 c => sub {return shift() + 34},
748 my @cont = sort %$deref;
749 if ("\t" eq "\011") { # ASCII
750 is("@cont", '23 5 fake foo');
752 else { # EBCDIC alpha-numeric sort order
753 is("@cont", 'fake foo 23 5');
755 my @keys = sort keys %$deref;
756 is("@keys", 'fake foo');
757 my @val = sort values %$deref;
759 is($deref->{foo}, 5);
760 is(defined $deref->{bar}, '');
763 push @keys, $key while $key = each %$deref;
765 is("@keys", 'fake foo');
766 is(exists $deref->{bar}, '');
767 is(exists $deref->{foo}, 1);
771 sub xxx_goto { goto &$deref }
773 my $srt = bless { c => sub {$b <=> $a}
776 my @sorted = sort srt 11, 2, 5, 1, 22;
777 is("@sorted", '22 11 5 2 1');
781 @sorted = sort $srt 11, 2, 5, 1, 22;
782 is("@sorted", '22 11 5 2 1');
784 is("@$deref", '11 12 13');
788 is($deref->[2], '13');
792 is($deref->[$l], '12');
793 # Repeated dereference
794 my $double = bless { h => $deref,
796 is($double->{foo}, 5);
801 use overload '%{}' => \&gethash, '@{}' => sub { ${shift()} };
809 tie %h, ref $self, $self;
813 sub TIEHASH { my $p = shift; bless \ shift, $p }
816 $fields{$_} = $i++ foreach qw{zero one two three};
818 my $self = ${shift()};
819 my $key = $fields{shift()};
820 defined $key or die "Out of band access";
821 $$self->[$key] = shift;
824 my $self = ${shift()};
825 my $key = $fields{shift()};
826 defined $key or die "Out of band access";
831 my $bar = new two_refs 3,4,5,6;
842 $bar = new two_refs_o 3,4,5,6;
850 use overload '%{}' => sub { ${shift()}->[1] },
851 '@{}' => sub { ${shift()}->[0] };
857 bless \ [$a, \%h], $p;
862 tie %h, ref $self, $self;
866 sub TIEHASH { my $p = shift; bless \ shift, $p }
869 $fields{$_} = $i++ foreach qw{zero one two three};
872 my $key = $fields{shift()};
873 defined $key or die "Out of band access";
878 my $key = $fields{shift()};
879 defined $key or die "Out of band access";
884 $bar = new two_refs_o 3,4,5,6;
892 @ISA = ('two_refs1');
895 $bar = new two_refs1_o 3,4,5,6;
903 use overload bool => sub { ${+shift} };
907 { my $bbbb = 0; $aaa = bless \$bbbb, B }
917 # check that overload isn't done twice by join
920 use overload '""' => sub { $c++ };
921 my $x = join '', bless([]), 'pq', bless([]);
925 # Test module-specific warning
927 # check the Odd number of arguments for overload::constant warning
929 local $SIG{__WARN__} = sub {$a = $_[0]} ;
930 $x = eval ' overload::constant "integer" ; ' ;
932 use warnings 'overload' ;
933 $x = eval ' overload::constant "integer" ; ' ;
934 like($a, qr/^Odd number of arguments for overload::constant at/);
938 # check the `$_[0]' is not an overloadable type warning
940 local $SIG{__WARN__} = sub {$a = $_[0]} ;
941 $x = eval ' overload::constant "fred" => sub {} ; ' ;
943 use warnings 'overload' ;
944 $x = eval ' overload::constant "fred" => sub {} ; ' ;
945 like($a, qr/^`fred' is not an overloadable type at/);
949 # check the `$_[1]' is not a code reference warning
951 local $SIG{__WARN__} = sub {$a = $_[0]} ;
952 $x = eval ' overload::constant "integer" => 1; ' ;
954 use warnings 'overload' ;
955 $x = eval ' overload::constant "integer" => 1; ' ;
956 like($a, qr/^`1' is not a code reference at/);
962 use overload '""' => sub { 3+shift->[0] },
963 '0+' => sub { 10+shift->[0] },
964 'int' => sub { 100+shift->[0] };
965 sub new {my $p = shift; bless [shift], $p}
968 use overload '""' => sub { 5+shift->[0] },
969 '0+' => sub { 30+shift->[0] },
970 'int' => sub { 'ov_int1'->new(1000+shift->[0]) };
971 sub new {my $p = shift; bless [shift], $p}
974 use overload '""' => sub { 2+shift->[0] },
975 '0+' => sub { 9+shift->[0] };
976 sub new {my $p = shift; bless [shift], $p}
980 my $x = new noov_int 11;
982 main::is("$int_x", 20);
985 main::is("$int_x", 131);
988 main::is("$int_x", 1054);
991 # make sure that we don't infinitely recurse
995 use overload '""' => sub { shift },
996 '0+' => sub { shift },
997 'bool' => sub { shift },
1000 # For some reason beyond me these have to be oks rather than likes.
1001 main::ok("$x" =~ /Recurse=ARRAY/);
1003 main::ok($x+0 =~ qr/Recurse=ARRAY/);
1006 # BugID 20010422.003
1010 'bool' => sub { return !$_[0]->is_zero() || undef; }
1016 return $self->{var} == 0;
1023 $self->{var} = shift;
1031 my $r = Foo->new(8);
1039 '""' => sub { return $_[0]->{var}; }
1046 $self->{var} = shift;
1053 my $utfvar = new utf8_o 200.2.1;
1054 is("$utfvar", 200.2.1); # 223 - stringify
1055 is("a$utfvar", "a".200.2.1); # 224 - overload via sv_2pv_flags
1057 # 225..227 -- more %{} tests. Hangs in 5.6.0, okay in later releases.
1058 # Basically this example implements strong encapsulation: if Hderef::import()
1059 # were to eval the overload code in the caller's namespace, the privatisation
1060 # would be quite transparent.
1062 use overload '%{}' => sub { (caller(0))[0] eq 'Foo' ? $_[0] : die "zap" };
1064 @Foo::ISA = 'Hderef';
1065 sub new { bless {}, shift }
1066 sub xet { @_ == 2 ? $_[0]->{$_[1]} :
1067 @_ == 3 ? ($_[0]->{$_[1]} = $_[2]) : undef }
1071 is ($a->xet('b'), 42);
1072 ok (!defined eval { $a->{b} });
1077 use overload '=' => sub { 42 },
1078 '++' => sub { my $x = ${$_[0]}; $_[0] };
1079 sub new { my $x = 42; bless \$x }
1083 local $SIG{__WARN__} = sub { $warn++ };
1092 my ($int, $out1, $out2);
1094 BEGIN { $int = 0; overload::constant 'integer' => sub {$int++; 17}; }
1098 is($int, 2, "#24313"); # 230
1099 is($out1, 17, "#24313"); # 231
1100 is($out2, 17, "#24313"); # 232
1105 use overload (qw(0+ numify fallback 1));
1112 sub numify { ${$_[0]} }
1117 use overload cmp => sub { 0 };
1118 package perl31793_fb;
1119 use overload cmp => sub { 0 }, fallback => 1;
1121 my $o = bless [], 'perl31793';
1122 my $of = bless [], 'perl31793_fb';
1123 my $no = bless [], 'no_overload';
1124 like(overload::StrVal(\"scalar"), qr/^SCALAR\(0x[0-9a-f]+\)$/);
1125 like(overload::StrVal([]), qr/^ARRAY\(0x[0-9a-f]+\)$/);
1126 like(overload::StrVal({}), qr/^HASH\(0x[0-9a-f]+\)$/);
1127 like(overload::StrVal(sub{1}), qr/^CODE\(0x[0-9a-f]+\)$/);
1128 like(overload::StrVal(\*GLOB), qr/^GLOB\(0x[0-9a-f]+\)$/);
1129 like(overload::StrVal(\$o), qr/^REF\(0x[0-9a-f]+\)$/);
1130 like(overload::StrVal(qr/a/), qr/^Regexp=REGEXP\(0x[0-9a-f]+\)$/);
1131 like(overload::StrVal($o), qr/^perl31793=ARRAY\(0x[0-9a-f]+\)$/);
1132 like(overload::StrVal($of), qr/^perl31793_fb=ARRAY\(0x[0-9a-f]+\)$/);
1133 like(overload::StrVal($no), qr/^no_overload=ARRAY\(0x[0-9a-f]+\)$/);
1136 # These are all check that overloaded values rather than reference addresses
1137 # are what is getting tested.
1138 my ($two, $one, $un, $deux) = map {new Numify $_} 2, 1, 1, 2;
1139 my ($ein, $zwei) = (1, 2);
1141 my %map = (one => 1, un => 1, ein => 1, deux => 2, two => 2, zwei => 2);
1142 foreach my $op (qw(<=> == != < <= > >=)) {
1143 foreach my $l (keys %map) {
1144 foreach my $r (keys %map) {
1145 my $ocode = "\$$l $op \$$r";
1146 my $rcode = "$map{$l} $op $map{$r}";
1148 my $got = eval $ocode;
1150 my $expect = eval $rcode;
1152 is ($got, $expect, $ocode) or print "# $rcode\n";
1157 # check that overloading works in regexes
1161 '""' => sub { "^$_[0][0]\$" },
1165 ? (ref $_[1] ? $_[1][0] : $_[1]) . ':' .$_[0][0]
1166 : $_[0][0] . ':' . (ref $_[1] ? $_[1][0] : $_[1])
1171 my $a = bless [ "a" ], 'Foo493';
1173 like('x:a', qr/x$a/);
1174 like('x:a:=', qr/x$a=$/);
1175 like('x:a:a:=', qr/x$a$a=$/);
1182 use overload qr => sub { qr/x/ }, fallback => 1;
1185 my $x = bless [], "QRonly";
1187 # like tries to be too clever, and decides that $x-stringified
1188 # doesn't look like a regex
1189 ok("x" =~ $x, "qr-only matches");
1190 ok("y" !~ $x, "qr-only doesn't match what it shouldn't");
1191 ok("xx" =~ /x$x/, "qr-only matches with concat");
1192 like("$x", qr/^QRonly=ARRAY/, "qr-only doesn't have string overload");
1194 my $qr = bless qr/y/, "QRonly";
1195 ok("x" =~ $qr, "qr with qr-overload uses overload");
1196 ok("y" !~ $qr, "qr with qr-overload uses overload");
1197 is("$qr", "".qr/y/, "qr with qr-overload stringify");
1200 ok("y" =~ $rx, "bare rx with qr-overload doesn't overload match");
1201 ok("x" !~ $rx, "bare rx with qr-overload doesn't overload match");
1202 is("$rx", "".qr/y/, "bare rx with qr-overload stringify");
1206 use overload qr => sub { qr/x/ }, q/""/ => sub { "y" };
1209 my $x = bless [], "QRandSTR";
1210 ok("x" =~ $x, "qr+str uses qr for match");
1211 ok("y" !~ $x, "qr+str uses qr for match");
1212 ok("xx" =~ /x$x/, "qr+str uses qr for match with concat");
1213 is("$x", "y", "qr+str uses str for stringify");
1215 my $qr = bless qr/z/, "QRandSTR";
1216 is("$qr", "y", "qr with qr+str uses str for stringify");
1217 ok("xx" =~ /x$x/, "qr with qr+str uses qr for match");
1220 ok("z" =~ $rx, "bare rx with qr+str doesn't overload match");
1221 is("$rx", "".qr/z/, "bare rx with qr+str doesn't overload stringify");
1225 use overload qr => sub { $_[0]->(@_) };
1228 use overload qr => sub { $_[0] };
1231 my $rx = bless sub { ${ qr/x/ } }, "QRany";
1232 ok("x" =~ $rx, "qr overload accepts a bare rx");
1233 ok("y" !~ $rx, "qr overload accepts a bare rx");
1235 my $str = bless sub { "x" }, "QRany";
1236 ok(!eval { "x" =~ $str }, "qr overload doesn't accept a string");
1237 like($@, qr/^Overloaded qr did not return a REGEXP/, "correct error");
1239 my $oqr = bless qr/z/, "QRandSTR";
1240 my $oqro = bless sub { $oqr }, "QRany";
1241 ok("z" =~ $oqro, "qr overload doesn't recurse");
1243 my $qrs = bless qr/z/, "QRself";
1244 ok("z" =~ $qrs, "qr overload can return self");
1248 use overload q/""/ => sub { "x" };
1251 use overload q/""/ => sub { "x" }, fallback => 1;
1254 my $fb = bless [], "STRonlyFB";
1255 ok("x" =~ $fb, "qr falls back to \"\"");
1256 ok("y" !~ $fb, "qr falls back to \"\"");
1258 my $nofb = bless [], "STRonly";
1259 ok("x" =~ $nofb, "qr falls back even without fallback");
1260 ok("y" !~ $nofb, "qr falls back even without fallback");
1265 my $twenty_three = 23;
1266 # Check that constant overloading propagates into evals
1267 BEGIN { overload::constant integer => sub { 23 } }
1268 is(eval "17", $twenty_three);
1274 bool => sub { shift->is_cool };
1277 $_[0]->{name} eq 'cool';
1282 bless $_[0], 'Brap';
1286 sub delete_with_self {
1289 bless $self, 'Brap';
1300 $obj = bless {name => 'cool'}, 'Sklorsh';
1302 ok(eval {if ($obj) {1}; 1}, $@ || 'reblessed into nonexistent namespace');
1304 $obj = bless {name => 'cool'}, 'Sklorsh';
1305 $obj->delete_with_self;
1306 ok (eval {if ($obj) {1}; 1}, $@);
1308 my $a = $b = {name => 'hot'};
1309 bless $b, 'Sklorsh';
1310 is(ref $a, 'Sklorsh');
1311 is(ref $b, 'Sklorsh');
1312 ok(!$b, "Expect overloaded boolean");
1313 ok(!$a, "Expect overloaded boolean");
1319 bool => sub { shift->{truth} eq 'yes' },
1320 '0+' => sub { shift->{truth} eq 'yes' ? '1' : '0' },
1321 '!' => sub { shift->{truth} eq 'no' },
1324 sub new { my $class = shift; bless { truth => shift }, $class }
1328 my $yes = Flrbbbbb->new('yes');
1330 $x = 1 if $yes; is($x, 1);
1331 $x = 2 unless $yes; is($x, 1);
1332 $x = 3 if !$yes; is($x, 1);
1333 $x = 4 unless !$yes; is($x, 4);
1335 my $no = Flrbbbbb->new('no');
1337 $x = 1 if $no; is($x, 0);
1338 $x = 2 unless $no; is($x, 2);
1339 $x = 3 if !$no; is($x, 3);
1340 $x = 4 unless !$no; is($x, 3);
1343 $x = 1 if !$no && $yes; is($x, 1);
1344 $x = 2 unless !$no && $yes; is($x, 1);
1345 $x = 3 if $no || !$yes; is($x, 1);
1346 $x = 4 unless $no || !$yes; is($x, 4);
1349 $x = 1 if !$no || !$yes; is($x, 1);
1350 $x = 2 unless !$no || !$yes; is($x, 1);
1351 $x = 3 if !$no && !$yes; is($x, 1);
1352 $x = 4 unless !$no && !$yes; is($x, 4);
1356 use Scalar::Util 'weaken';
1359 use overload '""' => sub {"CLiK KLAK"};
1366 $obj = bless do {my $a; \$a}, 'Shklitza';
1369 is ("$obj", "CLiK KLAK");
1370 is ("$ref", "CLiK KLAK");
1373 is ("$ref", "CLiK KLAK");
1375 bless $obj, 'Ksshfwoom';
1377 like ($obj, qr/^Ksshfwoom=/);
1378 like ($ref, qr/^Ksshfwoom=/);
1386 # bit operations have overloadable assignment variants too
1388 sub new { bless \$_[1], $_[0] }
1391 "&=" => sub { bit->new($_[0]->val . ' & ' . $_[1]->val) },
1392 "^=" => sub { bit->new($_[0]->val . ' ^ ' . $_[1]->val) },
1393 "|" => sub { bit->new($_[0]->val . ' | ' . $_[1]->val) }, # |= by fallback
1396 sub val { ${$_[0]} }
1400 my $a = bit->new(my $va = 'a');
1401 my $b = bit->new(my $vb = 'b');
1404 is($a->val, 'a & b', "overloaded &= works");
1406 my $c = bit->new(my $vc = 'c');
1409 is($b->val, 'b ^ c', "overloaded ^= works");
1411 my $d = bit->new(my $vd = 'd');
1414 is($c->val, 'c | d', "overloaded |= (by fallback) works");
1418 # comparison operators with nomethod (bug 41546)
1422 package nomethod_false;
1423 use overload nomethod => sub { $method = 'nomethod'; 0 };
1425 package nomethod_true;
1426 use overload nomethod => sub { $method= 'nomethod'; 'true' };
1430 local $SIG{__WARN__} = sub { $warning = $_[0] };
1432 my $f = bless [], 'nomethod_false';
1433 ($warning, $method) = ("", "");
1434 is($f eq 'whatever', 0, 'nomethod makes eq return 0');
1435 is($method, 'nomethod');
1437 my $t = bless [], 'nomethod_true';
1438 ($warning, $method) = ("", "");
1439 is($t eq 'whatever', 'true', 'nomethod makes eq return "true"');
1440 is($method, 'nomethod');
1441 is($warning, "", 'nomethod eq need not return number');
1444 package nomethod_false;
1445 use overload cmp => sub { $method = 'cmp'; 0 };
1447 $f = bless [], 'nomethod_false';
1448 ($warning, $method) = ("", "");
1449 ok($f eq 'whatever', 'eq falls back to cmp (nomethod not called)');
1453 package nomethod_true;
1454 use overload cmp => sub { $method = 'cmp'; 'true' };
1456 $t = bless [], 'nomethod_true';
1457 ($warning, $method) = ("", "");
1458 ok($t eq 'whatever', 'eq falls back to cmp (nomethod not called)');
1460 like($warning, qr/isn't numeric/, 'cmp should return number');
1465 # nomethod called for '!' after attempted fallback
1466 my $nomethod_called = 0;
1468 package nomethod_not;
1469 use overload nomethod => sub { $nomethod_called = 'yes'; };
1472 my $o = bless [], 'nomethod_not';
1475 is($nomethod_called, 'yes', "nomethod() is called for '!'");
1476 is($res, 'yes', "nomethod(..., '!') return value propagates");
1480 # Subtle bug pre 5.10, as a side effect of the overloading flag being
1481 # stored on the reference rather than the referent. Despite the fact that
1482 # objects can only be accessed via references (even internally), the
1483 # referent actually knows that it's blessed, not the references. So taking
1484 # a new, unrelated, reference to it gives an object. However, the
1485 # overloading-or-not flag was on the reference prior to 5.10, and taking
1486 # a new reference didn't (use to) copy it.
1490 use overload '""' => sub {${$_[0]}};
1493 return "$_[0], $_[1]";
1500 my $crunch_eth = bless \$string, $class;
1502 is("$crunch_eth", $string);
1503 is ($crunch_eth->Pie("Meat"), "$string, Meat");
1505 my $wham_eth = \$string;
1507 is("$wham_eth", $string,
1508 'This reference did not have overloading in 5.8.8 and earlier');
1509 is ($crunch_eth->Pie("Apple"), "$string, Apple");
1511 my $class = ref $wham_eth;
1514 # Bless it back into its own class!
1515 bless $wham_eth, $class;
1517 is("$wham_eth", $string);
1518 is ($crunch_eth->Pie("Blackbird"), "$string, Blackbird");
1523 use overload "0+" => sub { $_[0][0] += 1; 42 };
1524 package numify_self;
1525 use overload "0+" => sub { $_[0][0]++; $_[0] };
1526 package numify_other;
1527 use overload "0+" => sub { $_[0][0]++; $_[0][1] = bless [], 'numify_int' };
1528 package numify_by_fallback;
1529 use overload fallback => 1;
1532 my $o = bless [], 'numify_int';
1533 is(int($o), 42, 'numifies to integer');
1534 is($o->[0], 1, 'int() numifies only once');
1537 my $num_val = int($aref);
1538 my $r = bless $aref, 'numify_self';
1539 is(int($r), $num_val, 'numifies to self');
1540 is($r->[0], 1, 'int() numifies once when returning self');
1542 my $s = bless [], 'numify_other';
1543 is(int($s), 42, 'numifies to numification of other object');
1544 is($s->[0], 1, 'int() numifies once when returning other object');
1545 is($s->[1][0], 1, 'returned object numifies too');
1547 my $m = bless $aref, 'numify_by_fallback';
1548 is(int($m), $num_val, 'numifies to usual reference value');
1549 is(abs($m), $num_val, 'numifies to usual reference value');
1550 is(-$m, -$num_val, 'numifies to usual reference value');
1551 is(0+$m, $num_val, 'numifies to usual reference value');
1552 is($m+0, $num_val, 'numifies to usual reference value');
1553 is($m+$m, 2*$num_val, 'numifies to usual reference value');
1554 is(0-$m, -$num_val, 'numifies to usual reference value');
1555 is(1*$m, $num_val, 'numifies to usual reference value');
1556 is(int($m/1), $num_val, 'numifies to usual reference value');
1557 is($m%100, $num_val%100, 'numifies to usual reference value');
1558 is($m**1, $num_val, 'numifies to usual reference value');
1560 is(abs($aref), $num_val, 'abs() of ref');
1561 is(-$aref, -$num_val, 'negative of ref');
1562 is(0+$aref, $num_val, 'ref addition');
1563 is($aref+0, $num_val, 'ref addition');
1564 is($aref+$aref, 2*$num_val, 'ref addition');
1565 is(0-$aref, -$num_val, 'subtraction of ref');
1566 is(1*$aref, $num_val, 'multiplicaton of ref');
1567 is(int($aref/1), $num_val, 'division of ref');
1568 is($aref%100, $num_val%100, 'modulo of ref');
1569 is($aref**1, $num_val, 'exponentiation of ref');
1573 package CopyConstructorFallback;
1575 '++' => sub { "$_[0]"; $_[0] },
1577 sub new { bless {} => shift }
1581 my $o = CopyConstructorFallback->new;
1582 my $x = $o++; # would segfault
1584 is($x, $o, "copy constructor falls back to assignment (postinc)");
1585 is($y, $o, "copy constructor falls back to assignment (preinc)");
1588 # only scalar 'x' should currently overload
1596 'x' => sub { $x++; 1 },
1597 '0+' => sub { $n++; 1 },
1598 'nomethod' => sub { $nm++; 1 },
1609 ($x,$n,$nm) = (0,0,0);
1610 @a = ((1,2,$s) x $count);
1611 is("$x-$n-$nm", "0-0-0", 'repeat 1');
1613 ($x,$n,$nm) = (0,0,0);
1614 @a = ((1,$s,3) x $count);
1615 is("$x-$n-$nm", "0-0-0", 'repeat 2');
1617 ($x,$n,$nm) = (0,0,0);
1618 @a = ((1,2,3) x $s);
1619 is("$x-$n-$nm", "0-1-0", 'repeat 3');
1624 # RT #57012: magic items need to have mg_get() called before testing for
1625 # overload. Lack of this means that overloaded values returned by eg a
1626 # tied array didn't call overload methods.
1627 # We test here both a tied array and scalar, since the implementation of
1628 # tied arrays (and hashes) is such that in rvalue context, mg_get is
1629 # called prior to executing the op, while it isn't for a tied scalar.
1630 # We also check that return values are correctly tainted.
1631 # We try against two overload packages; one has all expected methods, the
1632 # other uses only fallback methods.
1636 # @tests holds a list of test cases. Each elem is an array ref with
1637 # the following entries:
1639 # * the value that the overload method should return
1641 # * the expression to be evaled. %s is replaced with the
1642 # variable being tested ($ta[0], $ts, or $plain)
1644 # * a string listing what functions we expect to be called.
1645 # Each method appends its name in parentheses, so "(=)(+)" means
1646 # we expect the copy constructor and then the add method to be
1649 # * like above, but what should be called for the fallback-only test
1650 # (in this case, nomethod() identifies itself as "(NM:*)" where *
1651 # is the op). If this value is undef, fallback tests are skipped.
1653 # * An array ref of expected counts of calls to FETCH/STORE.
1654 # The first three values are:
1655 # 1. the expected number of FETCHs for a tied array
1656 # 2. the expected number of FETCHs for a tied scalar
1657 # 3. the expected number of STOREs
1658 # If there are a further three elements present, then
1659 # these represent the expected counts for the fallback
1660 # version of the tests. If absent, they are assumed to
1661 # be the same as for the full method test
1663 # * Under the taint version of the tests, whether we expect
1664 # the result to be tainted (for example comparison ops
1665 # like '==' don't return a tainted value, even if their
1674 # A note on what methods to expect to be called, and
1675 # how many times FETCH/STORE is called:
1677 # Mutating ops (+=, ++ etc) trigger a copy ('='), since
1678 # the code can't distinguish between something that's been copied:
1679 # $a = foo->new(0); $b = $a; refcnt($$b) == 2
1680 # and overloaded objects stored in ties which will have extra
1681 # refcounts due to the tied_obj magic and entries on the tmps
1682 # stack when returning from FETCH etc. So we always copy.
1684 # This accounts for a '=', and an extra STORE.
1685 # We also have a FETCH returning the final value from the eval,
1686 # plus a FETCH in the overload subs themselves: ($_[0][0])
1687 # triggers one. However, tied aggregates have a mechanism to prevent
1688 # multiple fetches between STOREs, which means that the tied
1689 # hash skips doing a FETCH during '='.
1691 for (qw(+ - * / % ** << >> & | ^)) {
1693 $op = '%%' if $op eq '%';
1694 my $e = "%s $op= 3";
1696 # ARRAY FETCH: initial, sub+=, eval-return,
1697 # SCALAR FETCH: initial, sub=, sub+=, eval-return,
1698 # STORE: copy, mutator
1699 push @tests, [ 18, $e, "(=)($_=)", "(=)(NM:$_=)", [ 3, 4, 2 ], 1 ];
1702 "do { my \$arg = %s; \$_[2] ? (3 $op \$arg) : (\$arg $op 3) }";
1703 # ARRAY FETCH: initial
1704 # SCALAR FETCH: initial eval-return,
1705 push @tests, [ 18, "%s $op 3", "($_)", "(NM:$_)", [ 1, 2, 0 ], 1 ];
1706 push @tests, [ 18, "3 $op %s", "($_)", "(NM:$_)", [ 1, 2, 0 ], 1 ];
1709 # these use string fallback rather than nomethod
1712 my $e = "%s $op= 3";
1715 # ARRAY FETCH: initial, sub+=, eval-return,
1716 # SCALAR FETCH: initial, sub=, sub+=, eval-return,
1717 # STORE: copy, mutator
1718 # for fallback, we just stringify, so eval-return and copy skipped
1720 push @tests, [ 18, $e, "(=)($_=)", '("")',
1721 [ 3, 4, 2, 2, 3, 1 ], 1 ];
1724 "do { my \$arg = %s; \$_[2] ? (3 $op \$arg) : (\$arg $op 3) }";
1725 # ARRAY FETCH: initial
1726 # SCALAR FETCH: initial eval-return,
1727 # with fallback, we just stringify, so eval-return skipped,
1728 # but an extra FETCH happens in sub"", except for 'x',
1729 # which passes a copy of the RV to sub"", avoiding the
1732 push @tests, [ 18, "%s $op 3", "($_)", '("")',
1733 [ 1, 2, 0, 1, ($_ eq '.' ? 2 : 1), 0 ], 1 ];
1734 next if $_ eq 'x'; # repeat only overloads on LHS
1735 push @tests, [ 18, "3 $op %s", "($_)", '("")',
1736 [ 1, 2, 0, 1, 2, 0 ], 1 ];
1744 # ARRAY FETCH: initial, sub+=, eval-return,
1745 # SCALAR FETCH: initial, sub=, sub+=, eval-return,
1746 # STORE: copy, mutator
1747 [ 18, $pre, "(=)($_)(\"\")", "(=)(NM:$_)(\"\")", [ 3, 4, 2 ], 1 ],
1748 # ARRAY FETCH: initial, sub+=
1749 # SCALAR FETCH: initial, sub=, sub+=
1750 # STORE: copy, mutator
1751 [ 18, $post, "(=)($_)(\"\")", "(=)(NM:$_)(\"\")", [ 2, 3, 2 ], 1 ];
1754 # For the non-mutator ops, we have a initial FETCH,
1755 # an extra FETCH within the sub itself for the scalar option,
1758 for (qw(< <= > >= == != lt le gt ge eq ne)) {
1761 push @tests, [ 3, $e, "($_)", "(NM:$_)", [ 1, 2, 0 ], 0 ];
1766 push @tests, [ 3, $e, "($_)", "(NM:$_)", [ 1, 2, 0 ], 1 ];
1771 push @tests, [ 18, $e, "($_)", "(NM:$_)", [ 1, 2, 0 ], 1 ];
1773 for (qw(cos sin exp abs log sqrt int ~)) {
1776 push @tests, [ 1.23, $e, "($_)",
1777 ($_ eq 'int' ? '(0+)' : "(NM:$_)") , [ 1, 2, 0 ], 1 ];
1782 push @tests, [ 1.23, $e, "($_)", '(0+)', [ 1, 2, 0 ], 0 ];
1787 push @tests, [ 18, $e, '(neg)', '(NM:neg)', [ 1, 2, 0 ], 1 ];
1789 my $e = '(%s) ? 1 : 0';
1791 push @tests, [ 18, $e, '(bool)', '(0+)', [ 1, 2, 0 ], 0 ];
1793 # note: this is testing unary qr, not binary =~
1794 $subs{qr} = '(qr/%s/)';
1795 push @tests, [ "abc", '"abc" =~ (%s)', '(qr)', '("")', [ 1, 2, 0 ], 0 ];
1797 $e = '"abc" ~~ (%s)';
1799 push @tests, [ "abc", $e, '(~~)', '(NM:~~)', [ 1, 1, 0 ], 0 ];
1801 $subs{'-X'} = 'do { my $f = (%s);'
1802 . '$_[1] eq "r" ? (-r ($f)) :'
1803 . '$_[1] eq "e" ? (-e ($f)) :'
1804 . '$_[1] eq "f" ? (-f ($f)) :'
1805 . '$_[1] eq "l" ? (-l ($f)) :'
1806 . '$_[1] eq "t" ? (-t ($f)) :'
1807 . '$_[1] eq "T" ? (-T ($f)) : 0;}';
1808 # Note - we don't care what these file tests return, as
1809 # long as the tied and untied versions return the same value.
1810 # The flags below are chosen to test all uses of tryAMAGICftest_MG
1811 for (qw(r e f l t T)) {
1812 push @tests, [ 'TEST', "-$_ (%s)", '(-X)', '("")', [ 1, 2, 0 ], 0 ];
1815 $subs{'${}'} = '%s';
1816 push @tests, [ do {my $s=99; \$s}, '${%s}', '(${})', undef, [ 1, 1, 0 ], 0 ];
1818 # we skip testing '@{}' here because too much of this test
1819 # framework involves array dereferences!
1821 $subs{'%{}'} = '%s';
1822 push @tests, [ {qw(a 1 b 2 c 3)}, 'join "", sort keys %%{%s}',
1823 '(%{})', undef, [ 1, 1, 0 ], 0 ];
1825 $subs{'&{}'} = '%s';
1826 push @tests, [ sub {99}, 'do {&{%s} for 1,2}',
1827 '(&{})(&{})', undef, [ 2, 2, 0 ], 0 ];
1831 $subs{'*{}'} = '%s';
1832 push @tests, [ \*RT57012A, '*RT57012B = *{%s}; our $RT57012B',
1833 '(*{})', undef, [ 1, 1, 0 ], 0 ];
1835 my $iter_text = ("some random text\n" x 100) . $^X;
1836 open my $iter_fh, '<', \$iter_text
1837 or die "open of \$iter_text gave ($!)\n";
1838 $subs{'<>'} = '<$iter_fh>';
1839 push @tests, [ $iter_fh, '<%s>', '(<>)', undef, [ 1, 1, 0 ], 1 ];
1841 # eval should do tie, overload on its arg before checking taint */
1842 push @tests, [ '1;', 'eval q(eval %s); $@ =~ /Insecure/',
1843 '("")', '("")', [ 1, 2, 0 ], 0 ];
1846 for my $sub (keys %subs) {
1847 my $term = $subs{$sub};
1848 my $t = sprintf $term, '$_[0][0]';
1849 my $e ="sub { \$funcs .= '($sub)'; my \$r; if (\$use_int) {"
1850 . "use integer; \$r = ($t) } else { \$r = ($t) } \$r }";
1851 $subs{$sub} = eval $e;
1852 die "Compiling sub gave error:\n<$e>\n<$@>\n" if $@;
1863 "=" => sub { $funcs .= '(=)'; bless [ $_[0][0] ] },
1864 '0+' => sub { $funcs .= '(0+)'; 0 + $_[0][0] },
1865 '""' => sub { $funcs .= '("")'; "$_[0][0]" },
1868 package RT57012_OV_FB; # only contains fallback conversion functions
1871 "=" => sub { $funcs .= '(=)'; bless [ $_[0][0] ] },
1872 '0+' => sub { $funcs .= '(0+)'; 0 + $_[0][0] },
1873 '""' => sub { $funcs .= '("")'; "$_[0][0]" },
1875 $funcs .= "(NM:$_[3])";
1876 my $e = defined($_[1])
1879 ? "atan2(\$_[1],\$_[0][0])"
1880 : "atan2(\$_[0][0],\$_[1])"
1882 ? "\$_[1] $_[3] \$_[0][0]"
1883 : "\$_[0][0] $_[3] \$_[1]"
1886 : "$_[3](\$_[0][0])";
1889 use integer; $r = eval $e;
1894 ::diag("eval of nomethod <$e> gave <$@>") if $@;
1900 package RT57012_TIE_S;
1903 sub TIESCALAR { bless [ bless [ $tie_val ], $_[1] ] }
1904 sub FETCH { $fetches++; $_[0][0] }
1905 sub STORE { $stores++; $_[0][0] = $_[1] }
1907 package RT57012_TIE_A;
1909 sub TIEARRAY { bless [] }
1910 sub FETCH { $fetches++; $_[0][0] }
1911 sub STORE { $stores++; $_[0][$_[1]] = $_[2] }
1915 for my $test (@tests) {
1916 my ($val, $sub_term, $exp_funcs, $exp_fb_funcs,
1917 $exp_counts, $exp_taint) = @$test;
1921 # create tainted version of $val (unless its a ref)
1922 my $t = substr($^X,0,0);
1924 my $val1 = $val; # use a copy to avoid stringifying original
1925 $tainted_val = ref($val1) ? $val :
1926 ($val1 =~ /^[\d\.]+$/) ? $val+$t0 : $val.$t;
1928 $tie_val = $tainted_val;
1930 for my $int ('', 'use integer; ') {
1931 $use_int = ($int ne '');
1932 my $plain = $tainted_val;
1933 my $plain_term = $int . sprintf $sub_term, '$plain';
1934 my $exp = eval $plain_term;
1935 diag("eval of plain_term <$plain_term> gave <$@>") if $@;
1936 is(tainted($exp), $exp_taint,
1937 "<$plain_term> taint of expected return");
1939 for my $ov_pkg (qw(RT57012_OV RT57012_OV_FB)) {
1940 next if $ov_pkg eq 'RT57012_OV_FB'
1941 and not defined $exp_fb_funcs;
1942 my ($exp_fetch_a, $exp_fetch_s, $exp_store) =
1943 ($ov_pkg eq 'RT57012_OV' || @$exp_counts < 4)
1944 ? @$exp_counts[0,1,2]
1945 : @$exp_counts[3,4,5];
1947 tie my $ts, 'RT57012_TIE_S', $ov_pkg;
1948 tie my @ta, 'RT57012_TIE_A';
1949 $ta[0] = bless [ $tainted_val ], $ov_pkg;
1950 my $oload = bless [ $tainted_val ], $ov_pkg;
1952 for my $var ('$ta[0]', '$ts', '$oload',
1953 ($sub_term eq '<%s>' ? '${ts}' : ())
1960 my $res_term = $int . sprintf $sub_term, $var;
1961 my $desc = "<$res_term> $ov_pkg" ;
1962 my $res = eval $res_term;
1963 diag("eval of res_term $desc gave <$@>") if $@;
1964 # uniquely, the inc/dec ops return the original
1965 # ref rather than a copy, so stringify it to
1966 # find out if its tainted
1967 $res = "$res" if $res_term =~ /\+\+|--/;
1968 is(tainted($res), $exp_taint,
1969 "$desc taint of result return");
1970 is($res, $exp, "$desc return value");
1971 my $fns =($ov_pkg eq 'RT57012_OV_FB')
1972 ? $exp_fb_funcs : $exp_funcs;
1973 if ($var eq '$oload' && $res_term !~ /oload(\+\+|--)/) {
1974 # non-tied overloading doesn't trigger a copy
1975 # except for post inc/dec
1978 is($funcs, $fns, "$desc methods called");
1979 next if $var eq '$oload';
1980 my $exp_fetch = ($var eq '$ts') ?
1981 $exp_fetch_s : $exp_fetch_a;
1982 is($fetches, $exp_fetch, "$desc FETCH count");
1983 is($stores, $exp_store, "$desc STORE count");
1992 # Test overload from the main package
1994 '$^W = 1; use overload q\""\ => sub {"ning"}; print bless []',
1996 { switches => ['-wl'], stderr => 1 },
1997 'use overload from the main package'
2001 package blessed_methods;
2002 use overload '+' => sub {};
2003 bless overload::Method __PACKAGE__,'+';
2004 eval { overload::Method __PACKAGE__,'+' };
2005 ::is($@, '', 'overload::Method and blessed overload methods');
2009 # fallback to 'cmp' and '<=>' with heterogeneous operands
2011 my $not_found = 'no method found';
2016 bless \$n, ref $_[0] || $_[0];
2020 (${$_[0]} <=> ${$_[1]}) * ($_[2] ? -1 : 1);
2025 use overload '<=>' => 'cmp';
2029 use overload 'cmp' => 'cmp';
2032 my $n = NCmp->new(5);
2033 my $s = SCmp->new(3);
2036 eval { $res = $n > $s; };
2037 $res = $not_found if $@ =~ /$not_found/;
2038 is($res, 1, 'A>B using A<=> when B overloaded, no B<=>');
2040 eval { $res = $s < $n; };
2041 $res = $not_found if $@ =~ /$not_found/;
2042 is($res, 1, 'A<B using B<=> when A overloaded, no A<=>');
2044 eval { $res = $s lt $n; };
2045 $res = $not_found if $@ =~ /$not_found/;
2046 is($res, 1, 'A lt B using A:cmp when B overloaded, no B:cmp');
2048 eval { $res = $n gt $s; };
2049 $res = $not_found if $@ =~ /$not_found/;
2050 is($res, 1, 'A gt B using B:cmp when A overloaded, no A:cmp');
2052 my $o = NCmp->new(9);
2054 is($used, \$n, 'A < B uses <=> from A in preference to B');
2056 my $t = SCmp->new(7);
2058 is($used, \$s, 'A lt B uses cmp from A in preference to B');
2062 # Combinatorial testing of 'fallback' and 'nomethod'
2065 use overload '0+' => sub { ${$_[0]}; },
2069 my $n = @_ ? shift : 0;
2070 bless my $obj = \$n, ref $self || $self;
2074 my $s = "(${$_[0]} ";
2075 $s .= "nomethod, " if defined ${ref($_[0]).'::(nomethod'};
2076 my $fb = ${ref($_[0]).'::()'};
2077 $s .= "fb=" . (defined $fb ? 0 + $fb : 'undef') . ")";
2079 sub nomethod { "${$_[0]}.nomethod"; }
2081 # create classes for tests
2083 my @falls = (0, 'undef', 1);
2084 my @nomethods = ('', 'nomethod');
2085 my $not_found = 'no method found';
2086 for my $fall (@falls) {
2087 for my $nomethod (@nomethods) {
2088 my $nomethod_decl = $nomethod
2089 ? $nomethod . "=>'nomethod'," : '';
2091 package NuMB$fall$nomethod;
2093 use overload $nomethod_decl
2099 # operation and precedence of 'fallback' and 'nomethod'
2100 # for all combinations with 2 overloaded operands
2101 for my $nomethod2 (@nomethods) {
2102 for my $nomethod1 (@nomethods) {
2103 for my $fall2 (@falls) {
2104 my $pack2 = "NuMB$fall2$nomethod2";
2105 for my $fall1 (@falls) {
2106 my $pack1 = "NuMB$fall1$nomethod1";
2107 my ($test, $out, $exp);
2109 my \$x = $pack1->new(2);
2110 my \$y = $pack2->new(3);
2111 \$test = "\$x" . ' * ' . "\$y";
2114 $out = $not_found if $@ =~ /$not_found/;
2115 $exp = $nomethod1 ? '2.nomethod' :
2116 $nomethod2 ? '3.nomethod' :
2117 $fall1 eq '1' && $fall2 eq '1' ? 6
2119 is($out, $exp, "$test --> $exp");
2125 # operation of 'fallback' and 'nomethod'
2126 # where the other operand is not overloaded
2127 for my $nomethod (@nomethods) {
2128 for my $fall (@falls) {
2129 my ($test, $out, $exp);
2131 my \$x = NuMB$fall$nomethod->new(2);
2132 \$test = "\$x" . ' * 3';
2135 $out = $not_found if $@ =~ /$not_found/;
2136 $exp = $nomethod ? '2.nomethod' :
2139 is($out, $exp, "$test --> $exp");
2142 my \$x = NuMB$fall$nomethod->new(2);
2143 \$test = '3 * ' . "\$x";
2146 $out = $not_found if $@ =~ /$not_found/;
2147 is($out, $exp, "$test --> $exp");
2152 # since 5.6 overloaded <> was leaving an extra arg on the stack!
2156 use overload '<>' => sub { 11 };
2158 my $a = bless [], 'Iter1';
2160 my @a = (10, ($x = <$a>), 12);
2161 is ($a[0], 10, 'Iter1: a[0]');
2162 is ($a[1], 11, 'Iter1: a[1]');
2163 is ($a[2], 12, 'Iter1: a[2]');
2164 @a = (10, ($x .= <$a>), 12);
2165 is ($a[0], 10, 'Iter1: a[0] concat');
2166 is ($a[1], 1111, 'Iter1: a[1] concat');
2167 is ($a[2], 12, 'Iter1: a[2] concat');
2170 # Some tests for error messages
2173 use overload '+' => 'justice';
2175 ::like $@, qr/^Can't resolve method "justice" overloading "\+" in p(?x:
2176 )ackage "Justus" at /,
2177 'Error message when explicitly named overload method does not exist';
2180 our @ISA = 'JustYou';
2181 package JustYou { use overload '+' => 'injustice'; }
2184 ::like $@, qr/^Stub found while resolving method "\?{3}" overloadin(?x:
2185 )g "\+" in package "JustUs" at /,
2186 'Error message when sub stub is encountered';
2189 { # undefining the overload stash -- KEEP THIS TEST LAST
2191 use overload '+' => 'onion';
2192 $_ = \&overload::nil;
2195 ::ok(1, 'no crash when undefining %overload::');