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 use Test::More tests => 4880;
52 use Scalar::Util qw(tainted);
54 $a = new Oscalar "087";
59 is(ref $a, "Oscalar");
65 is(ref $c, "Oscalar");
71 is(ref $a, "Oscalar");
75 is(ref $b, "Oscalar");
78 is(ref $a, "Oscalar");
83 is(ref $c, "Oscalar");
86 is(ref $a, "Oscalar");
91 is(ref $b, "Oscalar");
94 is(ref $a, "Oscalar");
96 eval q[ package Oscalar; use overload ('++' => sub { $ {$_[0]}++;$_[0] } ) ];
100 is(ref $a, "Oscalar");
104 is(ref $b, "Oscalar");
107 is(ref $a, "Oscalar");
110 $dummy=bless \$dummy; # Now cache of method should be reloaded
116 is(ref $b, "Oscalar");
119 is(ref $a, "Oscalar");
121 undef $b; # Destroying updates tables too...
123 eval q[package Oscalar; use overload ('++' => sub { $ {$_[0]} += 2; $_[0] } ) ];
127 is(ref $a, "Oscalar");
131 is(ref $b, "Oscalar");
134 is(ref $a, "Oscalar");
137 $dummy=bless \$dummy; # Now cache of method should be reloaded
142 is(ref $b, "Oscalar");
145 is(ref $a, "Oscalar");
150 is(ref $b, "Oscalar");
153 is(ref $a, "Oscalar");
158 eval q[ package Oscalar; use overload ('=' => sub {$main::copies++;
160 local $new=$ {$_[0]};
165 is(ref $b, "Oscalar");
168 is(ref $a, "Oscalar");
172 is(ref $b, "Oscalar");
175 is(ref $a, "Oscalar");
180 is(ref $b, "Oscalar");
183 is(ref $a, "Oscalar");
189 is(ref $b, "Oscalar");
192 is(ref $a, "Oscalar");
198 is(ref $b, "Oscalar");
201 is(ref $a, "Oscalar");
204 eval q[package Oscalar; use overload ('+=' => sub {$ {$_[0]} += 3*$_[1];
206 $c=new Oscalar; # Cause rehash
211 is(ref $b, "Oscalar");
214 is(ref $a, "Oscalar");
219 is(ref $b, "Oscalar");
224 is(ref $b, "Oscalar");
230 is(ref $b, "Oscalar");
236 is(ref $b, "Oscalar");
240 eval q[package Oscalar;
241 use overload ('x' => sub {new Oscalar ( $_[2] ? "_.$_[1]._" x $ {$_[0]}
242 : "_.${$_[0]}._" x $_[1])}) ];
246 is($a, "_.yy.__.yy.__.yy._");
248 eval q[package Oscalar;
249 use overload ('.' => sub {new Oscalar ( $_[2] ?
250 "_.$_[1].__.$ {$_[0]}._"
251 : "_.$ {$_[0]}.__.$_[1]._")}) ];
255 is("b${a}c", "_._.b.__.xx._.__.c._");
257 # Check inheritance of overloading;
263 $aI = new OscalarI "$a";
264 is(ref $aI, "OscalarI");
267 is("b${aI}c", "_._.b.__.xx._.__.c._");
269 # Here we test blessing to a package updates hash
271 eval "package Oscalar; no overload '.'";
273 is("b${a}", "_.b.__.xx._");
276 is("b${a}c", "bxxc");
278 is("b${a}c", "bxxc");
280 # Negative overloading:
283 like($@, qr/no method found/);
288 sub { *{"Oscalar::$AUTOLOAD"} = sub {"_!_" . shift() . "_!_"} ;
289 goto &{"Oscalar::$AUTOLOAD"}};
291 eval "package Oscalar; sub comple; use overload '~' => 'comple'";
293 $na = eval { ~$a }; # Hash was not updated
294 like($@, qr/no method found/);
298 $na = eval { ~$a }; # Hash updated
299 warn "`$na', $@" if $@;
305 $na = eval { ~$aI }; # Hash was not updated
306 like($@, qr/no method found/);
316 eval "package Oscalar; sub rshft; use overload '>>' => 'rshft'";
318 $na = eval { $aI >> 1 }; # Hash was not updated
319 like($@, qr/no method found/);
325 $na = eval { $aI >> 1 };
331 # warn overload::Method($a, '0+'), "\n";
332 is(overload::Method($a, '0+'), \&Oscalar::numify);
333 is(overload::Method($aI,'0+'), \&Oscalar::numify);
334 ok(overload::Overloaded($aI));
335 ok(!overload::Overloaded('overload'));
337 ok(! defined overload::Method($aI, '<<'));
338 ok(! defined overload::Method($a, '<'));
340 like (overload::StrVal($aI), qr/^OscalarI=SCALAR\(0x[\da-fA-F]+\)$/);
341 is(overload::StrVal(\$aI), "@{[\$aI]}");
343 # Check overloading by methods (specified deep in the ISA tree).
347 sub Oscalar::lshft {"_<<_" . shift() . "_<<_"}
348 eval "package OscalarI; use overload '<<' => 'lshft', '|' => 'lshft'";
353 bless $aII, 'OscalarII';
354 bless \$fake, 'OscalarI'; # update the hash
355 is(($aI | 3), '_<<_xx_<<_');
357 is(($aII << 3), '_<<_087_<<_');
360 BEGIN { $int = 7; overload::constant 'integer' => sub {$int++; shift}; }
367 BEGIN { overload::constant 'integer' => sub {$int++; shift()+1}; }
376 BEGIN { $q = $qr = 7;
377 overload::constant 'q' => sub {$q++; push @q, shift, ($_[1] || 'none'); shift},
378 'qr' => sub {$qr++; push @qr, shift, ($_[1] || 'none'); shift}; }
381 $out2 = "a\a$foo,\,";
387 is($out1, 'f\'o\\o');
389 is($out2, "a\afoo,\,");
390 is("@q", "foo q f'o\\\\o q a\\a qq ,\\, qq");
392 is("@qr", "b\\b qq .\\. qq");
396 $_ = '!<b>!foo!<-.>!';
397 BEGIN { overload::constant 'q' => sub {push @q1, shift, ($_[1] || 'none'); "_<" . (shift) . ">_"},
398 'qr' => sub {push @qr1, shift, ($_[1] || 'none'); "!<" . (shift) . ">!"}; }
401 $out2 = "a\a$foo,\,";
411 s'first part'second part';
412 s/yet another/tail here/;
417 is($out1, '_<f\'o\\o>_');
418 is($out2, "_<a\a>_foo_<,\,>_");
419 is("@q1", "foo q f'o\\\\o q a\\a qq ,\\, qq oups
421 q second part q tail here s A-Z tr a-z tr");
422 is("@qr1", "b\\b qq .\\. qq try it q first part q yet another qq");
431 package symbolic; # Primitive symbolic calculator
432 use overload nomethod => \&wrap, '""' => \&str, '0+' => \&num,
433 '=' => \&cpy, '++' => \&inc, '--' => \&dec;
435 sub new { shift; bless ['n', @_] }
438 bless [@$self], ref $self;
440 sub inc { $_[0] = bless ['++', $_[0], 1]; }
441 sub dec { $_[0] = bless ['--', $_[0], 1]; }
443 my ($obj, $other, $inv, $meth) = @_;
444 if ($meth eq '++' or $meth eq '--') {
445 @$obj = ($meth, (bless [@$obj]), 1); # Avoid circular reference
448 ($obj, $other) = ($other, $obj) if $inv;
449 bless [$meth, $obj, $other];
452 my ($meth, $a, $b) = @{+shift};
453 $a = 'u' unless defined $a;
460 my %subr = ( 'n' => sub {$_[0]} );
461 foreach my $op (split " ", $overload::ops{with_assign}) {
462 $subr{$op} = $subr{"$op="} = eval "sub {shift() $op shift()}";
464 my @bins = qw(binary 3way_comparison num_comparison str_comparison);
465 foreach my $op (split " ", "@overload::ops{ @bins }") {
466 $subr{$op} = eval "sub {shift() $op shift()}";
468 foreach my $op (split " ", "@overload::ops{qw(unary func)}") {
469 $subr{$op} = eval "sub {$op shift()}";
471 $subr{'++'} = $subr{'+'};
472 $subr{'--'} = $subr{'-'};
475 my ($meth, $a, $b) = @{+shift};
476 my $subr = $subr{$meth}
477 or die "Do not know how to ($meth) in symbolic";
478 $a = $a->num if ref $a eq __PACKAGE__;
479 $b = $b->num if ref $b eq __PACKAGE__;
482 sub TIESCALAR { my $pack = shift; $pack->new(@_) }
484 sub nop { } # Around a bug
485 sub vars { my $p = shift; tie($_, $p), $_->nop foreach @_; }
494 my $foo = new symbolic 11;
496 is((sprintf "%d", $foo), '12');
497 is((sprintf "%d", $baz), '11');
500 is((sprintf "%d", $foo), '13');
501 is((sprintf "%d", $bar), '12');
502 is((sprintf "%d", $baz), '13');
505 is((sprintf "%d", $foo), '14');
506 is((sprintf "%d", $bar), '12');
507 is((sprintf "%d", $baz), '14');
508 is((sprintf "%d", $ban), '13');
511 is((sprintf "%d", $foo), '15');
512 is((sprintf "%d", $baz), '14');
513 is("$foo", '[++ [+= [++ [++ [n 11] 1] 1] 1] 1]');
517 my $iter = new symbolic 2;
518 my $side = new symbolic 1;
522 $cnt = $cnt - 1; # The "simple" way
523 $side = (sqrt(1 + $side**2) - 1)/$side;
525 my $pi = $side*(2**($iter+2));
526 is("$side", '[/ [- [sqrt [+ 1 [** [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1] [n 1]] 2]]] 1] [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1] [n 1]]]');
527 is((sprintf "%f", $pi), '3.182598');
531 my $iter = new symbolic 2;
532 my $side = new symbolic 1;
536 $side = (sqrt(1 + $side**2) - 1)/$side;
538 my $pi = $side*(2**($iter+2));
539 is("$side", '[/ [- [sqrt [+ 1 [** [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1] [n 1]] 2]]] 1] [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1] [n 1]]]');
540 is((sprintf "%f", $pi), '3.182598');
545 symbolic->vars($a, $b);
546 my $c = sqrt($a**2 + $b**2);
548 is((sprintf "%d", $c), '5');
550 is((sprintf "%d", $c), '13');
554 package symbolic1; # Primitive symbolic calculator
556 use overload nomethod => \&wrap, '""' => \&str, '0+' => \&num, '=' => \&cpy;
558 sub new { shift; bless ['n', @_] }
561 bless [@$self], ref $self;
564 my ($obj, $other, $inv, $meth) = @_;
565 if ($meth eq '++' or $meth eq '--') {
566 @$obj = ($meth, (bless [@$obj]), 1); # Avoid circular reference
569 ($obj, $other) = ($other, $obj) if $inv;
570 bless [$meth, $obj, $other];
573 my ($meth, $a, $b) = @{+shift};
574 $a = 'u' unless defined $a;
581 my %subr = ( 'n' => sub {$_[0]} );
582 foreach my $op (split " ", $overload::ops{with_assign}) {
583 $subr{$op} = $subr{"$op="} = eval "sub {shift() $op shift()}";
585 my @bins = qw(binary 3way_comparison num_comparison str_comparison);
586 foreach my $op (split " ", "@overload::ops{ @bins }") {
587 $subr{$op} = eval "sub {shift() $op shift()}";
589 foreach my $op (split " ", "@overload::ops{qw(unary func)}") {
590 $subr{$op} = eval "sub {$op shift()}";
592 $subr{'++'} = $subr{'+'};
593 $subr{'--'} = $subr{'-'};
596 my ($meth, $a, $b) = @{+shift};
597 my $subr = $subr{$meth}
598 or die "Do not know how to ($meth) in symbolic";
599 $a = $a->num if ref $a eq __PACKAGE__;
600 $b = $b->num if ref $b eq __PACKAGE__;
603 sub TIESCALAR { my $pack = shift; $pack->new(@_) }
605 sub nop { } # Around a bug
606 sub vars { my $p = shift; tie($_, $p), $_->nop 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--; }
709 # XXX iterator overload not intended to work with CORE::GLOBAL?
710 if (defined &CORE::GLOBAL::glob) {
716 my $iter = iterator->new(5);
719 $acc .= " $out" while $out = <${iter}>;
720 is($acc, ' 5 4 3 2 1 0');
721 $iter = iterator->new(5);
722 is(scalar <${iter}>, '5');
724 $acc .= " $out" while $out = <$iter>;
725 is($acc, ' 4 3 2 1 0');
729 use overload '%{}' => \&hderef, '&{}' => \&cderef,
730 '*{}' => \&gderef, '${}' => \&sderef, '@{}' => \&aderef;
731 sub new { my ($p, $v) = @_; bless \$v, $p }
733 my ($self, $key) = (shift, shift);
734 my $class = ref $self;
735 bless $self, 'deref::dummy'; # Disable overloading of %{}
736 my $out = $self->{$key};
737 bless $self, $class; # Restore overloading
740 sub hderef {shift->deref('h')}
741 sub aderef {shift->deref('a')}
742 sub cderef {shift->deref('c')}
743 sub gderef {shift->deref('g')}
744 sub sderef {shift->deref('s')}
747 my $deref = bless { h => { foo => 5 , fake => 23 },
748 c => sub {return shift() + 34},
754 my @cont = sort %$deref;
755 if ("\t" eq "\011") { # ASCII
756 is("@cont", '23 5 fake foo');
758 else { # EBCDIC alpha-numeric sort order
759 is("@cont", 'fake foo 23 5');
761 my @keys = sort keys %$deref;
762 is("@keys", 'fake foo');
763 my @val = sort values %$deref;
765 is($deref->{foo}, 5);
766 is(defined $deref->{bar}, '');
769 push @keys, $key while $key = each %$deref;
771 is("@keys", 'fake foo');
772 is(exists $deref->{bar}, '');
773 is(exists $deref->{foo}, 1);
777 sub xxx_goto { goto &$deref }
779 my $srt = bless { c => sub {$b <=> $a}
782 my @sorted = sort srt 11, 2, 5, 1, 22;
783 is("@sorted", '22 11 5 2 1');
787 @sorted = sort $srt 11, 2, 5, 1, 22;
788 is("@sorted", '22 11 5 2 1');
790 is("@$deref", '11 12 13');
794 is($deref->[2], '13');
798 is($deref->[$l], '12');
799 # Repeated dereference
800 my $double = bless { h => $deref,
802 is($double->{foo}, 5);
807 use overload '%{}' => \&gethash, '@{}' => sub { ${shift()} };
815 tie %h, ref $self, $self;
819 sub TIEHASH { my $p = shift; bless \ shift, $p }
822 $fields{$_} = $i++ foreach qw{zero one two three};
824 my $self = ${shift()};
825 my $key = $fields{shift()};
826 defined $key or die "Out of band access";
827 $$self->[$key] = shift;
830 my $self = ${shift()};
831 my $key = $fields{shift()};
832 defined $key or die "Out of band access";
837 my $bar = new two_refs 3,4,5,6;
848 $bar = new two_refs_o 3,4,5,6;
856 use overload '%{}' => sub { ${shift()}->[1] },
857 '@{}' => sub { ${shift()}->[0] };
863 bless \ [$a, \%h], $p;
868 tie %h, ref $self, $self;
872 sub TIEHASH { my $p = shift; bless \ shift, $p }
875 $fields{$_} = $i++ foreach qw{zero one two three};
878 my $key = $fields{shift()};
879 defined $key or die "Out of band access";
884 my $key = $fields{shift()};
885 defined $key or die "Out of band access";
890 $bar = new two_refs_o 3,4,5,6;
898 @ISA = ('two_refs1');
901 $bar = new two_refs1_o 3,4,5,6;
909 use overload bool => sub { ${+shift} };
913 { my $bbbb = 0; $aaa = bless \$bbbb, B }
923 # check that overload isn't done twice by join
926 use overload '""' => sub { $c++ };
927 my $x = join '', bless([]), 'pq', bless([]);
931 # Test module-specific warning
933 # check the Odd number of arguments for overload::constant warning
935 local $SIG{__WARN__} = sub {$a = $_[0]} ;
936 $x = eval ' overload::constant "integer" ; ' ;
938 use warnings 'overload' ;
939 $x = eval ' overload::constant "integer" ; ' ;
940 like($a, qr/^Odd number of arguments for overload::constant at/);
944 # check the `$_[0]' is not an overloadable type warning
946 local $SIG{__WARN__} = sub {$a = $_[0]} ;
947 $x = eval ' overload::constant "fred" => sub {} ; ' ;
949 use warnings 'overload' ;
950 $x = eval ' overload::constant "fred" => sub {} ; ' ;
951 like($a, qr/^`fred' is not an overloadable type at/);
955 # check the `$_[1]' is not a code reference warning
957 local $SIG{__WARN__} = sub {$a = $_[0]} ;
958 $x = eval ' overload::constant "integer" => 1; ' ;
960 use warnings 'overload' ;
961 $x = eval ' overload::constant "integer" => 1; ' ;
962 like($a, qr/^`1' is not a code reference at/);
968 use overload '""' => sub { 3+shift->[0] },
969 '0+' => sub { 10+shift->[0] },
970 'int' => sub { 100+shift->[0] };
971 sub new {my $p = shift; bless [shift], $p}
974 use overload '""' => sub { 5+shift->[0] },
975 '0+' => sub { 30+shift->[0] },
976 'int' => sub { 'ov_int1'->new(1000+shift->[0]) };
977 sub new {my $p = shift; bless [shift], $p}
980 use overload '""' => sub { 2+shift->[0] },
981 '0+' => sub { 9+shift->[0] };
982 sub new {my $p = shift; bless [shift], $p}
986 my $x = new noov_int 11;
988 main::is("$int_x", 20);
991 main::is("$int_x", 131);
994 main::is("$int_x", 1054);
997 # make sure that we don't infinitely recurse
1001 use overload '""' => sub { shift },
1002 '0+' => sub { shift },
1003 'bool' => sub { shift },
1006 # For some reason beyond me these have to be oks rather than likes.
1007 main::ok("$x" =~ /Recurse=ARRAY/);
1009 main::ok($x+0 =~ qr/Recurse=ARRAY/);
1012 # BugID 20010422.003
1016 'bool' => sub { return !$_[0]->is_zero() || undef; }
1022 return $self->{var} == 0;
1029 $self->{var} = shift;
1037 my $r = Foo->new(8);
1045 '""' => sub { return $_[0]->{var}; }
1052 $self->{var} = shift;
1059 my $utfvar = new utf8_o 200.2.1;
1060 is("$utfvar", 200.2.1); # 223 - stringify
1061 is("a$utfvar", "a".200.2.1); # 224 - overload via sv_2pv_flags
1063 # 225..227 -- more %{} tests. Hangs in 5.6.0, okay in later releases.
1064 # Basically this example implements strong encapsulation: if Hderef::import()
1065 # were to eval the overload code in the caller's namespace, the privatisation
1066 # would be quite transparent.
1068 use overload '%{}' => sub { (caller(0))[0] eq 'Foo' ? $_[0] : die "zap" };
1070 @Foo::ISA = 'Hderef';
1071 sub new { bless {}, shift }
1072 sub xet { @_ == 2 ? $_[0]->{$_[1]} :
1073 @_ == 3 ? ($_[0]->{$_[1]} = $_[2]) : undef }
1077 is ($a->xet('b'), 42);
1078 ok (!defined eval { $a->{b} });
1083 use overload '=' => sub { 42 },
1084 '++' => sub { my $x = ${$_[0]}; $_[0] };
1085 sub new { my $x = 42; bless \$x }
1089 local $SIG{__WARN__} = sub { $warn++ };
1098 my ($int, $out1, $out2);
1100 BEGIN { $int = 0; overload::constant 'integer' => sub {$int++; 17}; }
1104 is($int, 2, "#24313"); # 230
1105 is($out1, 17, "#24313"); # 231
1106 is($out2, 17, "#24313"); # 232
1111 use overload (qw(0+ numify fallback 1));
1118 sub numify { ${$_[0]} }
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]+\)$/);
1142 # These are all check that overloaded values rather than reference addresses
1143 # are what is getting tested.
1144 my ($two, $one, $un, $deux) = map {new Numify $_} 2, 1, 1, 2;
1145 my ($ein, $zwei) = (1, 2);
1147 my %map = (one => 1, un => 1, ein => 1, deux => 2, two => 2, zwei => 2);
1148 foreach my $op (qw(<=> == != < <= > >=)) {
1149 foreach my $l (keys %map) {
1150 foreach my $r (keys %map) {
1151 my $ocode = "\$$l $op \$$r";
1152 my $rcode = "$map{$l} $op $map{$r}";
1154 my $got = eval $ocode;
1156 my $expect = eval $rcode;
1158 is ($got, $expect, $ocode) or print "# $rcode\n";
1163 # check that overloading works in regexes
1167 '""' => sub { "^$_[0][0]\$" },
1171 ? (ref $_[1] ? $_[1][0] : $_[1]) . ':' .$_[0][0]
1172 : $_[0][0] . ':' . (ref $_[1] ? $_[1][0] : $_[1])
1177 my $a = bless [ "a" ], 'Foo493';
1179 like('x:a', qr/x$a/);
1180 like('x:a:=', qr/x$a=$/);
1181 like('x:a:a:=', qr/x$a$a=$/);
1188 use overload qr => sub { qr/x/ }, fallback => 1;
1191 my $x = bless [], "QRonly";
1193 # like tries to be too clever, and decides that $x-stringified
1194 # doesn't look like a regex
1195 ok("x" =~ $x, "qr-only matches");
1196 ok("y" !~ $x, "qr-only doesn't match what it shouldn't");
1197 ok("xx" =~ /x$x/, "qr-only matches with concat");
1198 like("$x", qr/^QRonly=ARRAY/, "qr-only doesn't have string overload");
1200 my $qr = bless qr/y/, "QRonly";
1201 ok("x" =~ $qr, "qr with qr-overload uses overload");
1202 ok("y" !~ $qr, "qr with qr-overload uses overload");
1203 is("$qr", "".qr/y/, "qr with qr-overload stringify");
1206 ok("y" =~ $rx, "bare rx with qr-overload doesn't overload match");
1207 ok("x" !~ $rx, "bare rx with qr-overload doesn't overload match");
1208 is("$rx", "".qr/y/, "bare rx with qr-overload stringify");
1212 use overload qr => sub { qr/x/ }, q/""/ => sub { "y" };
1215 my $x = bless [], "QRandSTR";
1216 ok("x" =~ $x, "qr+str uses qr for match");
1217 ok("y" !~ $x, "qr+str uses qr for match");
1218 ok("xx" =~ /x$x/, "qr+str uses qr for match with concat");
1219 is("$x", "y", "qr+str uses str for stringify");
1221 my $qr = bless qr/z/, "QRandSTR";
1222 is("$qr", "y", "qr with qr+str uses str for stringify");
1223 ok("xx" =~ /x$x/, "qr with qr+str uses qr for match");
1226 ok("z" =~ $rx, "bare rx with qr+str doesn't overload match");
1227 is("$rx", "".qr/z/, "bare rx with qr+str doesn't overload stringify");
1231 use overload qr => sub { $_[0]->(@_) };
1234 use overload qr => sub { $_[0] };
1237 my $rx = bless sub { ${ qr/x/ } }, "QRany";
1238 ok("x" =~ $rx, "qr overload accepts a bare rx");
1239 ok("y" !~ $rx, "qr overload accepts a bare rx");
1241 my $str = bless sub { "x" }, "QRany";
1242 ok(!eval { "x" =~ $str }, "qr overload doesn't accept a string");
1243 like($@, qr/^Overloaded qr did not return a REGEXP/, "correct error");
1245 my $oqr = bless qr/z/, "QRandSTR";
1246 my $oqro = bless sub { $oqr }, "QRany";
1247 ok("z" =~ $oqro, "qr overload doesn't recurse");
1249 my $qrs = bless qr/z/, "QRself";
1250 ok("z" =~ $qrs, "qr overload can return self");
1254 use overload q/""/ => sub { "x" };
1257 use overload q/""/ => sub { "x" }, fallback => 1;
1260 my $fb = bless [], "STRonlyFB";
1261 ok("x" =~ $fb, "qr falls back to \"\"");
1262 ok("y" !~ $fb, "qr falls back to \"\"");
1264 my $nofb = bless [], "STRonly";
1265 ok("x" =~ $nofb, "qr falls back even without fallback");
1266 ok("y" !~ $nofb, "qr falls back even without fallback");
1271 my $twenty_three = 23;
1272 # Check that constant overloading propagates into evals
1273 BEGIN { overload::constant integer => sub { 23 } }
1274 is(eval "17", $twenty_three);
1280 bool => sub { shift->is_cool };
1283 $_[0]->{name} eq 'cool';
1288 bless $_[0], 'Brap';
1292 sub delete_with_self {
1295 bless $self, 'Brap';
1306 $obj = bless {name => 'cool'}, 'Sklorsh';
1308 ok(eval {if ($obj) {1}; 1}, $@ || 'reblessed into nonexistent namespace');
1310 $obj = bless {name => 'cool'}, 'Sklorsh';
1311 $obj->delete_with_self;
1312 ok (eval {if ($obj) {1}; 1}, $@);
1314 my $a = $b = {name => 'hot'};
1315 bless $b, 'Sklorsh';
1316 is(ref $a, 'Sklorsh');
1317 is(ref $b, 'Sklorsh');
1318 ok(!$b, "Expect overloaded boolean");
1319 ok(!$a, "Expect overloaded boolean");
1325 bool => sub { shift->{truth} eq 'yes' },
1326 '0+' => sub { shift->{truth} eq 'yes' ? '1' : '0' },
1327 '!' => sub { shift->{truth} eq 'no' },
1330 sub new { my $class = shift; bless { truth => shift }, $class }
1334 my $yes = Flrbbbbb->new('yes');
1336 $x = 1 if $yes; is($x, 1);
1337 $x = 2 unless $yes; is($x, 1);
1338 $x = 3 if !$yes; is($x, 1);
1339 $x = 4 unless !$yes; is($x, 4);
1341 my $no = Flrbbbbb->new('no');
1343 $x = 1 if $no; is($x, 0);
1344 $x = 2 unless $no; is($x, 2);
1345 $x = 3 if !$no; is($x, 3);
1346 $x = 4 unless !$no; is($x, 3);
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);
1355 $x = 1 if !$no || !$yes; is($x, 1);
1356 $x = 2 unless !$no || !$yes; is($x, 1);
1357 $x = 3 if !$no && !$yes; is($x, 1);
1358 $x = 4 unless !$no && !$yes; is($x, 4);
1362 local $TODO = 'Test-Simple handling of overloads changed with 0.95_01';
1364 use Scalar::Util 'weaken';
1367 use overload '""' => sub {"CLiK KLAK"};
1374 $obj = bless do {my $a; \$a}, 'Shklitza';
1377 is ($obj, "CLiK KLAK");
1378 is ($ref, "CLiK KLAK");
1381 is ($ref, "CLiK KLAK");
1383 bless $obj, 'Ksshfwoom';
1385 like ($obj, qr/^Ksshfwoom=/);
1386 like ($ref, qr/^Ksshfwoom=/);
1394 # bit operations have overloadable assignment variants too
1396 sub new { bless \$_[1], $_[0] }
1399 "&=" => sub { bit->new($_[0]->val . ' & ' . $_[1]->val) },
1400 "^=" => sub { bit->new($_[0]->val . ' ^ ' . $_[1]->val) },
1401 "|" => sub { bit->new($_[0]->val . ' | ' . $_[1]->val) }, # |= by fallback
1404 sub val { ${$_[0]} }
1408 my $a = bit->new(my $va = 'a');
1409 my $b = bit->new(my $vb = 'b');
1412 is($a->val, 'a & b', "overloaded &= works");
1414 my $c = bit->new(my $vc = 'c');
1417 is($b->val, 'b ^ c', "overloaded ^= works");
1419 my $d = bit->new(my $vd = 'd');
1422 is($c->val, 'c | d', "overloaded |= (by fallback) works");
1426 # comparison operators with nomethod (bug 41546)
1430 package nomethod_false;
1431 use overload nomethod => sub { $method = 'nomethod'; 0 };
1433 package nomethod_true;
1434 use overload nomethod => sub { $method= 'nomethod'; 'true' };
1438 local $SIG{__WARN__} = sub { $warning = $_[0] };
1440 my $f = bless [], 'nomethod_false';
1441 ($warning, $method) = ("", "");
1442 is($f eq 'whatever', 0, 'nomethod makes eq return 0');
1443 is($method, 'nomethod');
1445 my $t = bless [], 'nomethod_true';
1446 ($warning, $method) = ("", "");
1447 is($t eq 'whatever', 'true', 'nomethod makes eq return "true"');
1448 is($method, 'nomethod');
1449 is($warning, "", 'nomethod eq need not return number');
1452 package nomethod_false;
1453 use overload cmp => sub { $method = 'cmp'; 0 };
1455 $f = bless [], 'nomethod_false';
1456 ($warning, $method) = ("", "");
1457 ok($f eq 'whatever', 'eq falls back to cmp (nomethod not called)');
1461 package nomethod_true;
1462 use overload cmp => sub { $method = 'cmp'; 'true' };
1464 $t = bless [], 'nomethod_true';
1465 ($warning, $method) = ("", "");
1466 ok($t eq 'whatever', 'eq falls back to cmp (nomethod not called)');
1468 like($warning, qr/isn't numeric/, 'cmp should return number');
1473 # nomethod called for '!' after attempted fallback
1474 my $nomethod_called = 0;
1476 package nomethod_not;
1477 use overload nomethod => sub { $nomethod_called = 'yes'; };
1480 my $o = bless [], 'nomethod_not';
1483 is($nomethod_called, 'yes', "nomethod() is called for '!'");
1484 is($res, 'yes', "nomethod(..., '!') return value propagates");
1488 # Subtle bug pre 5.10, as a side effect of the overloading flag being
1489 # stored on the reference rather than the referent. Despite the fact that
1490 # objects can only be accessed via references (even internally), the
1491 # referent actually knows that it's blessed, not the references. So taking
1492 # a new, unrelated, reference to it gives an object. However, the
1493 # overloading-or-not flag was on the reference prior to 5.10, and taking
1494 # a new reference didn't (use to) copy it.
1498 use overload '""' => sub {${$_[0]}};
1501 return "$_[0], $_[1]";
1508 my $crunch_eth = bless \$string, $class;
1510 is("$crunch_eth", $string);
1511 is ($crunch_eth->Pie("Meat"), "$string, Meat");
1513 my $wham_eth = \$string;
1515 is("$wham_eth", $string,
1516 'This reference did not have overloading in 5.8.8 and earlier');
1517 is ($crunch_eth->Pie("Apple"), "$string, Apple");
1519 my $class = ref $wham_eth;
1522 # Bless it back into its own class!
1523 bless $wham_eth, $class;
1525 is("$wham_eth", $string);
1526 is ($crunch_eth->Pie("Blackbird"), "$string, Blackbird");
1531 use overload "0+" => sub { $_[0][0] += 1; 42 };
1532 package numify_self;
1533 use overload "0+" => sub { $_[0][0]++; $_[0] };
1534 package numify_other;
1535 use overload "0+" => sub { $_[0][0]++; $_[0][1] = bless [], 'numify_int' };
1536 package numify_by_fallback;
1537 use overload fallback => 1;
1540 my $o = bless [], 'numify_int';
1541 is(int($o), 42, 'numifies to integer');
1542 is($o->[0], 1, 'int() numifies only once');
1545 my $num_val = int($aref);
1546 my $r = bless $aref, 'numify_self';
1547 is(int($r), $num_val, 'numifies to self');
1548 is($r->[0], 1, 'int() numifies once when returning self');
1550 my $s = bless [], 'numify_other';
1551 is(int($s), 42, 'numifies to numification of other object');
1552 is($s->[0], 1, 'int() numifies once when returning other object');
1553 is($s->[1][0], 1, 'returned object numifies too');
1555 my $m = bless $aref, 'numify_by_fallback';
1556 is(int($m), $num_val, 'numifies to usual reference value');
1557 is(abs($m), $num_val, 'numifies to usual reference value');
1558 is(-$m, -$num_val, 'numifies to usual reference value');
1559 is(0+$m, $num_val, 'numifies to usual reference value');
1560 is($m+0, $num_val, 'numifies to usual reference value');
1561 is($m+$m, 2*$num_val, 'numifies to usual reference value');
1562 is(0-$m, -$num_val, 'numifies to usual reference value');
1563 is(1*$m, $num_val, 'numifies to usual reference value');
1564 is(int($m/1), $num_val, 'numifies to usual reference value');
1565 is($m%100, $num_val%100, 'numifies to usual reference value');
1566 is($m**1, $num_val, 'numifies to usual reference value');
1568 is(abs($aref), $num_val, 'abs() of ref');
1569 is(-$aref, -$num_val, 'negative of ref');
1570 is(0+$aref, $num_val, 'ref addition');
1571 is($aref+0, $num_val, 'ref addition');
1572 is($aref+$aref, 2*$num_val, 'ref addition');
1573 is(0-$aref, -$num_val, 'subtraction of ref');
1574 is(1*$aref, $num_val, 'multiplicaton of ref');
1575 is(int($aref/1), $num_val, 'division of ref');
1576 is($aref%100, $num_val%100, 'modulo of ref');
1577 is($aref**1, $num_val, 'exponentiation of ref');
1581 package CopyConstructorFallback;
1583 '++' => sub { "$_[0]"; $_[0] },
1585 sub new { bless {} => shift }
1589 my $o = CopyConstructorFallback->new;
1590 my $x = $o++; # would segfault
1592 is($x, $o, "copy constructor falls back to assignment (postinc)");
1593 is($y, $o, "copy constructor falls back to assignment (preinc)");
1596 # only scalar 'x' should currently overload
1604 'x' => sub { $x++; 1 },
1605 '0+' => sub { $n++; 1 },
1606 'nomethod' => sub { $nm++; 1 },
1617 ($x,$n,$nm) = (0,0,0);
1618 @a = ((1,2,$s) x $count);
1619 is("$x-$n-$nm", "0-0-0", 'repeat 1');
1621 ($x,$n,$nm) = (0,0,0);
1622 @a = ((1,$s,3) x $count);
1623 is("$x-$n-$nm", "0-0-0", 'repeat 2');
1625 ($x,$n,$nm) = (0,0,0);
1626 @a = ((1,2,3) x $s);
1627 is("$x-$n-$nm", "0-1-0", 'repeat 3');
1632 # RT #57012: magic items need to have mg_get() called before testing for
1633 # overload. Lack of this means that overloaded values returned by eg a
1634 # tied array didn't call overload methods.
1635 # We test here both a tied array and scalar, since the implementation of
1636 # tied arrays (and hashes) is such that in rvalue context, mg_get is
1637 # called prior to executing the op, while it isn't for a tied scalar.
1638 # We also check that return values are correctly tainted.
1639 # We try against two overload packages; one has all expected methods, the
1640 # other uses only fallback methods.
1644 # @tests holds a list of test cases. Each elem is an array ref with
1645 # the following entries:
1647 # * the value that the overload method should return
1649 # * the expression to be evaled. %s is replaced with the
1650 # variable being tested ($ta[0], $ts, or $plain)
1652 # * a string listing what functions we expect to be called.
1653 # Each method appends its name in parentheses, so "(=)(+)" means
1654 # we expect the copy constructor and then the add method to be
1657 # * like above, but what should be called for the fallback-only test
1658 # (in this case, nomethod() identifies itself as "(NM:*)" where *
1659 # is the op). If this value is undef, fallback tests are skipped.
1661 # * An array ref of expected counts of calls to FETCH/STORE.
1662 # The first three values are:
1663 # 1. the expected number of FETCHs for a tied array
1664 # 2. the expected number of FETCHs for a tied scalar
1665 # 3. the expected number of STOREs
1666 # If there are a further three elements present, then
1667 # these represent the expected counts for the fallback
1668 # version of the tests. If absent, they are assumed to
1669 # be the same as for the full method test
1671 # * Under the taint version of the tests, whether we expect
1672 # the result to be tainted (for example comparison ops
1673 # like '==' don't return a tainted value, even if their
1682 # A note on what methods to expect to be called, and
1683 # how many times FETCH/STORE is called:
1685 # Mutating ops (+=, ++ etc) trigger a copy ('='), since
1686 # the code can't distingish between something that's been copied:
1687 # $a = foo->new(0); $b = $a; refcnt($$b) == 2
1688 # and overloaded objects stored in ties which will have extra
1689 # refcounts due to the tied_obj magic and entries on the tmps
1690 # stack when returning from FETCH etc. So we always copy.
1692 # This accounts for a '=', and an extra STORE.
1693 # We also have a FETCH returning the final value from the eval,
1694 # plus a FETCH in the overload subs themselves: ($_[0][0])
1695 # triggers one. However, tied agregates have a mechanism to prevent
1696 # multiple fetches between STOREs, which means that the tied
1697 # hash skips doing a FETCH during '='.
1699 for (qw(+ - * / % ** << >> & | ^)) {
1701 $op = '%%' if $op eq '%';
1702 my $e = "%s $op= 3";
1704 # ARRAY FETCH: initial, sub+=, eval-return,
1705 # SCALAR FETCH: initial, sub=, sub+=, eval-return,
1706 # STORE: copy, mutator
1707 push @tests, [ 18, $e, "(=)($_=)", "(=)(NM:$_=)", [ 3, 4, 2 ], 1 ];
1710 "do { my \$arg = %s; \$_[2] ? (3 $op \$arg) : (\$arg $op 3) }";
1711 # ARRAY FETCH: initial
1712 # SCALAR FETCH: initial eval-return,
1713 push @tests, [ 18, "%s $op 3", "($_)", "(NM:$_)", [ 1, 2, 0 ], 1 ];
1714 push @tests, [ 18, "3 $op %s", "($_)", "(NM:$_)", [ 1, 2, 0 ], 1 ];
1717 # these use string fallback rather than nomethod
1720 my $e = "%s $op= 3";
1723 # ARRAY FETCH: initial, sub+=, eval-return,
1724 # SCALAR FETCH: initial, sub=, sub+=, eval-return,
1725 # STORE: copy, mutator
1726 # for fallback, we just stringify, so eval-return and copy skipped
1728 push @tests, [ 18, $e, "(=)($_=)", '("")',
1729 [ 3, 4, 2, 2, 3, 1 ], 1 ];
1732 "do { my \$arg = %s; \$_[2] ? (3 $op \$arg) : (\$arg $op 3) }";
1733 # ARRAY FETCH: initial
1734 # SCALAR FETCH: initial eval-return,
1735 # with fallback, we just stringify, so eval-return skipped,
1736 # but an extra FETCH happens in sub"", except for 'x',
1737 # which passes a copy of the RV to sub"", avoiding the
1740 push @tests, [ 18, "%s $op 3", "($_)", '("")',
1741 [ 1, 2, 0, 1, ($_ eq '.' ? 2 : 1), 0 ], 1 ];
1742 next if $_ eq 'x'; # repeat only overloads on LHS
1743 push @tests, [ 18, "3 $op %s", "($_)", '("")',
1744 [ 1, 2, 0, 1, 2, 0 ], 1 ];
1752 # ARRAY FETCH: initial, sub+=, eval-return,
1753 # SCALAR FETCH: initial, sub=, sub+=, eval-return,
1754 # STORE: copy, mutator
1755 [ 18, $pre, "(=)($_)(\"\")", "(=)(NM:$_)(\"\")", [ 3, 4, 2 ], 1 ],
1756 # ARRAY FETCH: initial, sub+=
1757 # SCALAR FETCH: initial, sub=, sub+=
1758 # STORE: copy, mutator
1759 [ 18, $post, "(=)($_)(\"\")", "(=)(NM:$_)(\"\")", [ 2, 3, 2 ], 1 ];
1762 # For the non-mutator ops, we have a initial FETCH,
1763 # an extra FETCH within the sub itself for the scalar option,
1766 for (qw(< <= > >= == != lt le gt ge eq ne)) {
1769 push @tests, [ 3, $e, "($_)", "(NM:$_)", [ 1, 2, 0 ], 0 ];
1774 push @tests, [ 3, $e, "($_)", "(NM:$_)", [ 1, 2, 0 ], 1 ];
1779 push @tests, [ 18, $e, "($_)", "(NM:$_)", [ 1, 2, 0 ], 1 ];
1781 for (qw(cos sin exp abs log sqrt int ~)) {
1784 push @tests, [ 1.23, $e, "($_)",
1785 ($_ eq 'int' ? '(0+)' : "(NM:$_)") , [ 1, 2, 0 ], 1 ];
1790 push @tests, [ 1.23, $e, "($_)", '(0+)', [ 1, 2, 0 ], 0 ];
1795 push @tests, [ 18, $e, '(neg)', '(NM:neg)', [ 1, 2, 0 ], 1 ];
1797 my $e = '(%s) ? 1 : 0';
1799 push @tests, [ 18, $e, '(bool)', '(0+)', [ 1, 2, 0 ], 0 ];
1801 # note: this is testing unary qr, not binary =~
1802 $subs{qr} = '(qr/%s/)';
1803 push @tests, [ "abc", '"abc" =~ (%s)', '(qr)', '("")', [ 1, 2, 0 ], 0 ];
1805 $e = '"abc" ~~ (%s)';
1807 push @tests, [ "abc", $e, '(~~)', '(NM:~~)', [ 1, 1, 0 ], 0 ];
1809 $subs{'-X'} = 'do { my $f = (%s);'
1810 . '$_[1] eq "r" ? (-r ($f)) :'
1811 . '$_[1] eq "e" ? (-e ($f)) :'
1812 . '$_[1] eq "f" ? (-f ($f)) :'
1813 . '$_[1] eq "l" ? (-l ($f)) :'
1814 . '$_[1] eq "t" ? (-t ($f)) :'
1815 . '$_[1] eq "T" ? (-T ($f)) : 0;}';
1816 # Note - we don't care what these filetests return, as
1817 # long as the tied and untied versions return the same value.
1818 # The flags below are chosen to test all uses of tryAMAGICftest_MG
1819 for (qw(r e f l t T)) {
1820 push @tests, [ 'TEST', "-$_ (%s)", '(-X)', '("")', [ 1, 2, 0 ], 0 ];
1823 $subs{'${}'} = '%s';
1824 push @tests, [ do {my $s=99; \$s}, '${%s}', '(${})', undef, [ 1, 1, 0 ], 0 ];
1826 # we skip testing '@{}' here because too much of this test
1827 # framework involves array dereferences!
1829 $subs{'%{}'} = '%s';
1830 push @tests, [ {qw(a 1 b 2 c 3)}, 'join "", sort keys %%{%s}',
1831 '(%{})', undef, [ 1, 2, 0 ], 0 ];
1833 $subs{'&{}'} = '%s';
1834 push @tests, [ sub {99}, 'do {&{%s} for 1,2}',
1835 '(&{})(&{})', undef, [ 2, 2, 0 ], 0 ];
1839 $subs{'*{}'} = '%s';
1840 push @tests, [ \*RT57012A, '*RT57012B = *{%s}; our $RT57012B',
1841 '(*{})', undef, [ 1, 1, 0 ], 0 ];
1845 # eval should do tie, overload on its arg before checking taint */
1846 push @tests, [ '1;', 'eval q(eval %s); $@ =~ /Insecure/',
1847 '("")', '("")', [ 1, 2, 0 ], 0 ];
1850 for my $sub (keys %subs) {
1851 my $term = $subs{$sub};
1852 my $t = sprintf $term, '$_[0][0]';
1853 my $e ="sub { \$funcs .= '($sub)'; my \$r; if (\$use_int) {"
1854 . "use integer; \$r = ($t) } else { \$r = ($t) } \$r }";
1855 $subs{$sub} = eval $e;
1856 die "Compiling sub gave error:\n<$e>\n<$@>\n" if $@;
1867 "=" => sub { $funcs .= '(=)'; bless [ $_[0][0] ] },
1868 '0+' => sub { $funcs .= '(0+)'; 0 + $_[0][0] },
1869 '""' => sub { $funcs .= '("")'; "$_[0][0]" },
1872 package RT57012_OV_FB; # only contains fallback conversion functions
1875 "=" => sub { $funcs .= '(=)'; bless [ $_[0][0] ] },
1876 '0+' => sub { $funcs .= '(0+)'; 0 + $_[0][0] },
1877 '""' => sub { $funcs .= '("")'; "$_[0][0]" },
1879 $funcs .= "(NM:$_[3])";
1880 my $e = defined($_[1])
1883 ? "atan2(\$_[1],\$_[0][0])"
1884 : "atan2(\$_[0][0],\$_[1])"
1886 ? "\$_[1] $_[3] \$_[0][0]"
1887 : "\$_[0][0] $_[3] \$_[1]"
1890 : "$_[3](\$_[0][0])";
1893 use integer; $r = eval $e;
1898 ::diag("eval of nomethod <$e> gave <$@>") if $@;
1904 package RT57012_TIE_S;
1907 sub TIESCALAR { bless [ bless [ $tie_val ], $_[1] ] }
1908 sub FETCH { $fetches++; $_[0][0] }
1909 sub STORE { $stores++; $_[0][0] = $_[1] }
1911 package RT57012_TIE_A;
1913 sub TIEARRAY { bless [] }
1914 sub FETCH { $fetches++; $_[0][0] }
1915 sub STORE { $stores++; $_[0][$_[1]] = $_[2] }
1919 for my $test (@tests) {
1920 my ($val, $sub_term, $exp_funcs, $exp_fb_funcs,
1921 $exp_counts, $exp_taint) = @$test;
1925 # create tainted version of $val (unless its a ref)
1926 my $t = substr($^X,0,0);
1928 my $val1 = $val; # use a copy to avoid stringifying original
1929 $tainted_val = ref($val1) ? $val :
1930 ($val1 =~ /^[\d\.]+$/) ? $val+$t0 : $val.$t;
1932 $tie_val = $tainted_val;
1934 for my $int ('', 'use integer; ') {
1935 $use_int = ($int ne '');
1936 my $plain = $tainted_val;
1937 my $plain_term = $int . sprintf $sub_term, '$plain';
1938 my $exp = eval $plain_term;
1939 diag("eval of plain_term <$plain_term> gave <$@>") if $@;
1940 is(tainted($exp), $exp_taint,
1941 "<$plain_term> taint of expected return");
1943 for my $ov_pkg (qw(RT57012_OV RT57012_OV_FB)) {
1944 # the deref ops don't support fallback
1945 next if $ov_pkg eq 'RT57012_OV_FB'
1946 and not defined $exp_fb_funcs;
1947 my ($exp_fetch_a, $exp_fetch_s, $exp_store) =
1948 ($ov_pkg eq 'RT57012_OV' || @$exp_counts < 4)
1949 ? @$exp_counts[0,1,2]
1950 : @$exp_counts[3,4,5];
1952 tie my $ts, 'RT57012_TIE_S', $ov_pkg;
1953 tie my @ta, 'RT57012_TIE_A';
1954 $ta[0] = bless [ $tainted_val ], $ov_pkg;
1955 my $oload = bless [ $tainted_val ], $ov_pkg;
1957 for my $var ('$ta[0]', '$ts', '$oload') {
1963 my $res_term = $int . sprintf $sub_term, $var;
1964 my $desc = "<$res_term> $ov_pkg" ;
1965 my $res = eval $res_term;
1966 diag("eval of res_term $desc gave <$@>") if $@;
1967 # uniquely, the inc/dec ops return tthe original
1968 # ref rather than a copy, so stringify it to
1969 # find out if its tainted
1970 $res = "$res" if $res_term =~ /\+\+|--/;
1971 is(tainted($res), $exp_taint,
1972 "$desc taint of result return");
1973 is($res, $exp, "$desc return value");
1974 my $fns =($ov_pkg eq 'RT57012_OV_FB')
1975 ? $exp_fb_funcs : $exp_funcs;
1976 if ($var eq '$oload' && $res_term !~ /oload(\+\+|--)/) {
1977 # non-tied overloading doesn't trigger a copy
1978 # except for post inc/dec
1981 is($funcs, $fns, "$desc methods called");
1982 next if $var eq '$oload';
1983 my $exp_fetch = ($var eq '$ts') ?
1984 $exp_fetch_s : $exp_fetch_a;
1985 is($fetches, $exp_fetch, "$desc FETCH count");
1986 is($stores, $exp_store, "$desc STORE count");