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 => 605;
53 $a = new Oscalar "087";
58 is(ref $a, "Oscalar");
64 is(ref $c, "Oscalar");
70 is(ref $a, "Oscalar");
74 is(ref $b, "Oscalar");
77 is(ref $a, "Oscalar");
82 is(ref $c, "Oscalar");
85 is(ref $a, "Oscalar");
90 is(ref $b, "Oscalar");
93 is(ref $a, "Oscalar");
95 eval q[ package Oscalar; use overload ('++' => sub { $ {$_[0]}++;$_[0] } ) ];
99 is(ref $a, "Oscalar");
103 is(ref $b, "Oscalar");
106 is(ref $a, "Oscalar");
109 $dummy=bless \$dummy; # Now cache of method should be reloaded
115 is(ref $b, "Oscalar");
118 is(ref $a, "Oscalar");
120 undef $b; # Destroying updates tables too...
122 eval q[package Oscalar; use overload ('++' => sub { $ {$_[0]} += 2; $_[0] } ) ];
126 is(ref $a, "Oscalar");
130 is(ref $b, "Oscalar");
133 is(ref $a, "Oscalar");
136 $dummy=bless \$dummy; # Now cache of method should be reloaded
141 is(ref $b, "Oscalar");
144 is(ref $a, "Oscalar");
149 is(ref $b, "Oscalar");
152 is(ref $a, "Oscalar");
157 eval q[ package Oscalar; use overload ('=' => sub {$main::copies++;
159 local $new=$ {$_[0]};
164 is(ref $b, "Oscalar");
167 is(ref $a, "Oscalar");
171 is(ref $b, "Oscalar");
174 is(ref $a, "Oscalar");
179 is(ref $b, "Oscalar");
182 is(ref $a, "Oscalar");
188 is(ref $b, "Oscalar");
191 is(ref $a, "Oscalar");
197 is(ref $b, "Oscalar");
200 is(ref $a, "Oscalar");
203 eval q[package Oscalar; use overload ('+=' => sub {$ {$_[0]} += 3*$_[1];
205 $c=new Oscalar; # Cause rehash
210 is(ref $b, "Oscalar");
213 is(ref $a, "Oscalar");
218 is(ref $b, "Oscalar");
223 is(ref $b, "Oscalar");
229 is(ref $b, "Oscalar");
235 is(ref $b, "Oscalar");
239 eval q[package Oscalar;
240 use overload ('x' => sub {new Oscalar ( $_[2] ? "_.$_[1]._" x $ {$_[0]}
241 : "_.${$_[0]}._" x $_[1])}) ];
245 is($a, "_.yy.__.yy.__.yy._");
247 eval q[package Oscalar;
248 use overload ('.' => sub {new Oscalar ( $_[2] ?
249 "_.$_[1].__.$ {$_[0]}._"
250 : "_.$ {$_[0]}.__.$_[1]._")}) ];
254 is("b${a}c", "_._.b.__.xx._.__.c._");
256 # Check inheritance of overloading;
262 $aI = new OscalarI "$a";
263 is(ref $aI, "OscalarI");
266 is("b${aI}c", "_._.b.__.xx._.__.c._");
268 # Here we test blessing to a package updates hash
270 eval "package Oscalar; no overload '.'";
272 is("b${a}", "_.b.__.xx._");
275 is("b${a}c", "bxxc");
277 is("b${a}c", "bxxc");
279 # Negative overloading:
282 like($@, qr/no method found/);
287 sub { *{"Oscalar::$AUTOLOAD"} = sub {"_!_" . shift() . "_!_"} ;
288 goto &{"Oscalar::$AUTOLOAD"}};
290 eval "package Oscalar; sub comple; use overload '~' => 'comple'";
292 $na = eval { ~$a }; # Hash was not updated
293 like($@, qr/no method found/);
297 $na = eval { ~$a }; # Hash updated
298 warn "`$na', $@" if $@;
304 $na = eval { ~$aI }; # Hash was not updated
305 like($@, qr/no method found/);
315 eval "package Oscalar; sub rshft; use overload '>>' => 'rshft'";
317 $na = eval { $aI >> 1 }; # Hash was not updated
318 like($@, qr/no method found/);
324 $na = eval { $aI >> 1 };
330 # warn overload::Method($a, '0+'), "\n";
331 is(overload::Method($a, '0+'), \&Oscalar::numify);
332 is(overload::Method($aI,'0+'), \&Oscalar::numify);
333 ok(overload::Overloaded($aI));
334 ok(!overload::Overloaded('overload'));
336 ok(! defined overload::Method($aI, '<<'));
337 ok(! defined overload::Method($a, '<'));
339 like (overload::StrVal($aI), qr/^OscalarI=SCALAR\(0x[\da-fA-F]+\)$/);
340 is(overload::StrVal(\$aI), "@{[\$aI]}");
342 # Check overloading by methods (specified deep in the ISA tree).
346 sub Oscalar::lshft {"_<<_" . shift() . "_<<_"}
347 eval "package OscalarI; use overload '<<' => 'lshft', '|' => 'lshft'";
352 bless $aII, 'OscalarII';
353 bless \$fake, 'OscalarI'; # update the hash
354 is(($aI | 3), '_<<_xx_<<_');
356 is(($aII << 3), '_<<_087_<<_');
359 BEGIN { $int = 7; overload::constant 'integer' => sub {$int++; shift}; }
366 BEGIN { overload::constant 'integer' => sub {$int++; shift()+1}; }
375 BEGIN { $q = $qr = 7;
376 overload::constant 'q' => sub {$q++; push @q, shift, ($_[1] || 'none'); shift},
377 'qr' => sub {$qr++; push @qr, shift, ($_[1] || 'none'); shift}; }
380 $out2 = "a\a$foo,\,";
386 is($out1, 'f\'o\\o');
388 is($out2, "a\afoo,\,");
389 is("@q", "foo q f'o\\\\o q a\\a qq ,\\, qq");
391 is("@qr", "b\\b qq .\\. qq");
395 $_ = '!<b>!foo!<-.>!';
396 BEGIN { overload::constant 'q' => sub {push @q1, shift, ($_[1] || 'none'); "_<" . (shift) . ">_"},
397 'qr' => sub {push @qr1, shift, ($_[1] || 'none'); "!<" . (shift) . ">!"}; }
400 $out2 = "a\a$foo,\,";
410 s'first part'second part';
411 s/yet another/tail here/;
416 is($out1, '_<f\'o\\o>_');
417 is($out2, "_<a\a>_foo_<,\,>_");
418 is("@q1", "foo q f'o\\\\o q a\\a qq ,\\, qq oups
420 q second part q tail here s A-Z tr a-z tr");
421 is("@qr1", "b\\b qq .\\. qq try it q first part q yet another qq");
430 package symbolic; # Primitive symbolic calculator
431 use overload nomethod => \&wrap, '""' => \&str, '0+' => \&num,
432 '=' => \&cpy, '++' => \&inc, '--' => \&dec;
434 sub new { shift; bless ['n', @_] }
437 bless [@$self], ref $self;
439 sub inc { $_[0] = bless ['++', $_[0], 1]; }
440 sub dec { $_[0] = bless ['--', $_[0], 1]; }
442 my ($obj, $other, $inv, $meth) = @_;
443 if ($meth eq '++' or $meth eq '--') {
444 @$obj = ($meth, (bless [@$obj]), 1); # Avoid circular reference
447 ($obj, $other) = ($other, $obj) if $inv;
448 bless [$meth, $obj, $other];
451 my ($meth, $a, $b) = @{+shift};
452 $a = 'u' unless defined $a;
459 my %subr = ( 'n' => sub {$_[0]} );
460 foreach my $op (split " ", $overload::ops{with_assign}) {
461 $subr{$op} = $subr{"$op="} = eval "sub {shift() $op shift()}";
463 my @bins = qw(binary 3way_comparison num_comparison str_comparison);
464 foreach my $op (split " ", "@overload::ops{ @bins }") {
465 $subr{$op} = eval "sub {shift() $op shift()}";
467 foreach my $op (split " ", "@overload::ops{qw(unary func)}") {
468 $subr{$op} = eval "sub {$op shift()}";
470 $subr{'++'} = $subr{'+'};
471 $subr{'--'} = $subr{'-'};
474 my ($meth, $a, $b) = @{+shift};
475 my $subr = $subr{$meth}
476 or die "Do not know how to ($meth) in symbolic";
477 $a = $a->num if ref $a eq __PACKAGE__;
478 $b = $b->num if ref $b eq __PACKAGE__;
481 sub TIESCALAR { my $pack = shift; $pack->new(@_) }
483 sub nop { } # Around a bug
484 sub vars { my $p = shift; tie($_, $p), $_->nop foreach @_; }
493 my $foo = new symbolic 11;
495 is((sprintf "%d", $foo), '12');
496 is((sprintf "%d", $baz), '11');
499 is((sprintf "%d", $foo), '13');
500 is((sprintf "%d", $bar), '12');
501 is((sprintf "%d", $baz), '13');
504 is((sprintf "%d", $foo), '14');
505 is((sprintf "%d", $bar), '12');
506 is((sprintf "%d", $baz), '14');
507 is((sprintf "%d", $ban), '13');
510 is((sprintf "%d", $foo), '15');
511 is((sprintf "%d", $baz), '14');
512 is("$foo", '[++ [+= [++ [++ [n 11] 1] 1] 1] 1]');
516 my $iter = new symbolic 2;
517 my $side = new symbolic 1;
521 $cnt = $cnt - 1; # The "simple" way
522 $side = (sqrt(1 + $side**2) - 1)/$side;
524 my $pi = $side*(2**($iter+2));
525 is("$side", '[/ [- [sqrt [+ 1 [** [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1] [n 1]] 2]]] 1] [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1] [n 1]]]');
526 is((sprintf "%f", $pi), '3.182598');
530 my $iter = new symbolic 2;
531 my $side = new symbolic 1;
535 $side = (sqrt(1 + $side**2) - 1)/$side;
537 my $pi = $side*(2**($iter+2));
538 is("$side", '[/ [- [sqrt [+ 1 [** [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1] [n 1]] 2]]] 1] [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1] [n 1]]]');
539 is((sprintf "%f", $pi), '3.182598');
544 symbolic->vars($a, $b);
545 my $c = sqrt($a**2 + $b**2);
547 is((sprintf "%d", $c), '5');
549 is((sprintf "%d", $c), '13');
553 package symbolic1; # Primitive symbolic calculator
555 use overload nomethod => \&wrap, '""' => \&str, '0+' => \&num, '=' => \&cpy;
557 sub new { shift; bless ['n', @_] }
560 bless [@$self], ref $self;
563 my ($obj, $other, $inv, $meth) = @_;
564 if ($meth eq '++' or $meth eq '--') {
565 @$obj = ($meth, (bless [@$obj]), 1); # Avoid circular reference
568 ($obj, $other) = ($other, $obj) if $inv;
569 bless [$meth, $obj, $other];
572 my ($meth, $a, $b) = @{+shift};
573 $a = 'u' unless defined $a;
580 my %subr = ( 'n' => sub {$_[0]} );
581 foreach my $op (split " ", $overload::ops{with_assign}) {
582 $subr{$op} = $subr{"$op="} = eval "sub {shift() $op shift()}";
584 my @bins = qw(binary 3way_comparison num_comparison str_comparison);
585 foreach my $op (split " ", "@overload::ops{ @bins }") {
586 $subr{$op} = eval "sub {shift() $op shift()}";
588 foreach my $op (split " ", "@overload::ops{qw(unary func)}") {
589 $subr{$op} = eval "sub {$op shift()}";
591 $subr{'++'} = $subr{'+'};
592 $subr{'--'} = $subr{'-'};
595 my ($meth, $a, $b) = @{+shift};
596 my $subr = $subr{$meth}
597 or die "Do not know how to ($meth) in symbolic";
598 $a = $a->num if ref $a eq __PACKAGE__;
599 $b = $b->num if ref $b eq __PACKAGE__;
602 sub TIESCALAR { my $pack = shift; $pack->new(@_) }
604 sub nop { } # Around a bug
605 sub vars { my $p = shift; tie($_, $p), $_->nop foreach @_; }
614 my $foo = new symbolic1 11;
616 is((sprintf "%d", $foo), '12');
617 is((sprintf "%d", $baz), '11');
620 is((sprintf "%d", $foo), '13');
621 is((sprintf "%d", $bar), '12');
622 is((sprintf "%d", $baz), '13');
625 is((sprintf "%d", $foo), '14');
626 is((sprintf "%d", $bar), '12');
627 is((sprintf "%d", $baz), '14');
628 is((sprintf "%d", $ban), '13');
631 is((sprintf "%d", $foo), '15');
632 is((sprintf "%d", $baz), '14');
633 is("$foo", '[++ [+= [++ [++ [n 11] 1] 1] 1] 1]');
637 my $iter = new symbolic1 2;
638 my $side = new symbolic1 1;
642 $cnt = $cnt - 1; # The "simple" way
643 $side = (sqrt(1 + $side**2) - 1)/$side;
645 my $pi = $side*(2**($iter+2));
646 is("$side", '[/ [- [sqrt [+ 1 [** [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1] [n 1]] 2]]] 1] [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1] [n 1]]]');
647 is((sprintf "%f", $pi), '3.182598');
651 my $iter = new symbolic1 2;
652 my $side = new symbolic1 1;
656 $side = (sqrt(1 + $side**2) - 1)/$side;
658 my $pi = $side*(2**($iter+2));
659 is("$side", '[/ [- [sqrt [+ 1 [** [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1] [n 1]] 2]]] 1] [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1] [n 1]]]');
660 is((sprintf "%f", $pi), '3.182598');
665 symbolic1->vars($a, $b);
666 my $c = sqrt($a**2 + $b**2);
668 is((sprintf "%d", $c), '5');
670 is((sprintf "%d", $c), '13');
674 package two_face; # Scalars with separate string and
676 sub new { my $p = shift; bless [@_], $p }
677 use overload '""' => \&str, '0+' => \&num, fallback => 1;
683 my $seven = new two_face ("vii", 7);
684 is((sprintf "seven=$seven, seven=%d, eight=%d", $seven, $seven+1),
685 'seven=vii, seven=7, eight=8');
686 is(scalar ($seven =~ /i/), '1');
691 use overload 'cmp' => \∁
692 sub new { my ($p, $v) = @_; bless \$v, $p }
693 sub comp { my ($x,$y) = @_; ($$x * 3 % 10) <=> ($$y * 3 % 10) or $$x cmp $$y }
696 my @arr = map sorting->new($_), 0..12;
697 my @sorted1 = sort @arr;
698 my @sorted2 = map $$_, @sorted1;
699 is("@sorted2", '0 10 7 4 1 11 8 5 12 2 9 6 3');
703 use overload '<>' => \&iter;
704 sub new { my ($p, $v) = @_; bless \$v, $p }
705 sub iter { my ($x) = @_; return undef if $$x < 0; return $$x--; }
708 # XXX iterator overload not intended to work with CORE::GLOBAL?
709 if (defined &CORE::GLOBAL::glob) {
715 my $iter = iterator->new(5);
718 $acc .= " $out" while $out = <${iter}>;
719 is($acc, ' 5 4 3 2 1 0');
720 $iter = iterator->new(5);
721 is(scalar <${iter}>, '5');
723 $acc .= " $out" while $out = <$iter>;
724 is($acc, ' 4 3 2 1 0');
728 use overload '%{}' => \&hderef, '&{}' => \&cderef,
729 '*{}' => \&gderef, '${}' => \&sderef, '@{}' => \&aderef;
730 sub new { my ($p, $v) = @_; bless \$v, $p }
732 my ($self, $key) = (shift, shift);
733 my $class = ref $self;
734 bless $self, 'deref::dummy'; # Disable overloading of %{}
735 my $out = $self->{$key};
736 bless $self, $class; # Restore overloading
739 sub hderef {shift->deref('h')}
740 sub aderef {shift->deref('a')}
741 sub cderef {shift->deref('c')}
742 sub gderef {shift->deref('g')}
743 sub sderef {shift->deref('s')}
746 my $deref = bless { h => { foo => 5 , fake => 23 },
747 c => sub {return shift() + 34},
753 my @cont = sort %$deref;
754 if ("\t" eq "\011") { # ASCII
755 is("@cont", '23 5 fake foo');
757 else { # EBCDIC alpha-numeric sort order
758 is("@cont", 'fake foo 23 5');
760 my @keys = sort keys %$deref;
761 is("@keys", 'fake foo');
762 my @val = sort values %$deref;
764 is($deref->{foo}, 5);
765 is(defined $deref->{bar}, '');
768 push @keys, $key while $key = each %$deref;
770 is("@keys", 'fake foo');
771 is(exists $deref->{bar}, '');
772 is(exists $deref->{foo}, 1);
776 sub xxx_goto { goto &$deref }
778 my $srt = bless { c => sub {$b <=> $a}
781 my @sorted = sort srt 11, 2, 5, 1, 22;
782 is("@sorted", '22 11 5 2 1');
786 @sorted = sort $srt 11, 2, 5, 1, 22;
787 is("@sorted", '22 11 5 2 1');
789 is("@$deref", '11 12 13');
793 is($deref->[2], '13');
797 is($deref->[$l], '12');
798 # Repeated dereference
799 my $double = bless { h => $deref,
801 is($double->{foo}, 5);
806 use overload '%{}' => \&gethash, '@{}' => sub { ${shift()} };
814 tie %h, ref $self, $self;
818 sub TIEHASH { my $p = shift; bless \ shift, $p }
821 $fields{$_} = $i++ foreach qw{zero one two three};
823 my $self = ${shift()};
824 my $key = $fields{shift()};
825 defined $key or die "Out of band access";
826 $$self->[$key] = shift;
829 my $self = ${shift()};
830 my $key = $fields{shift()};
831 defined $key or die "Out of band access";
836 my $bar = new two_refs 3,4,5,6;
847 $bar = new two_refs_o 3,4,5,6;
855 use overload '%{}' => sub { ${shift()}->[1] },
856 '@{}' => sub { ${shift()}->[0] };
862 bless \ [$a, \%h], $p;
867 tie %h, ref $self, $self;
871 sub TIEHASH { my $p = shift; bless \ shift, $p }
874 $fields{$_} = $i++ foreach qw{zero one two three};
877 my $key = $fields{shift()};
878 defined $key or die "Out of band access";
883 my $key = $fields{shift()};
884 defined $key or die "Out of band access";
889 $bar = new two_refs_o 3,4,5,6;
897 @ISA = ('two_refs1');
900 $bar = new two_refs1_o 3,4,5,6;
908 use overload bool => sub { ${+shift} };
912 { my $bbbb = 0; $aaa = bless \$bbbb, B }
922 # check that overload isn't done twice by join
925 use overload '""' => sub { $c++ };
926 my $x = join '', bless([]), 'pq', bless([]);
930 # Test module-specific warning
932 # check the Odd number of arguments for overload::constant warning
934 local $SIG{__WARN__} = sub {$a = $_[0]} ;
935 $x = eval ' overload::constant "integer" ; ' ;
937 use warnings 'overload' ;
938 $x = eval ' overload::constant "integer" ; ' ;
939 like($a, qr/^Odd number of arguments for overload::constant at/);
943 # check the `$_[0]' is not an overloadable type warning
945 local $SIG{__WARN__} = sub {$a = $_[0]} ;
946 $x = eval ' overload::constant "fred" => sub {} ; ' ;
948 use warnings 'overload' ;
949 $x = eval ' overload::constant "fred" => sub {} ; ' ;
950 like($a, qr/^`fred' is not an overloadable type at/);
954 # check the `$_[1]' is not a code reference warning
956 local $SIG{__WARN__} = sub {$a = $_[0]} ;
957 $x = eval ' overload::constant "integer" => 1; ' ;
959 use warnings 'overload' ;
960 $x = eval ' overload::constant "integer" => 1; ' ;
961 like($a, qr/^`1' is not a code reference at/);
967 use overload '""' => sub { 3+shift->[0] },
968 '0+' => sub { 10+shift->[0] },
969 'int' => sub { 100+shift->[0] };
970 sub new {my $p = shift; bless [shift], $p}
973 use overload '""' => sub { 5+shift->[0] },
974 '0+' => sub { 30+shift->[0] },
975 'int' => sub { 'ov_int1'->new(1000+shift->[0]) };
976 sub new {my $p = shift; bless [shift], $p}
979 use overload '""' => sub { 2+shift->[0] },
980 '0+' => sub { 9+shift->[0] };
981 sub new {my $p = shift; bless [shift], $p}
985 my $x = new noov_int 11;
987 main::is("$int_x", 20);
990 main::is("$int_x", 131);
993 main::is("$int_x", 1054);
996 # make sure that we don't infinitely recurse
1000 use overload '""' => sub { shift },
1001 '0+' => sub { shift },
1002 'bool' => sub { shift },
1005 # For some reason beyond me these have to be oks rather than likes.
1006 main::ok("$x" =~ /Recurse=ARRAY/);
1008 main::ok($x+0 =~ qr/Recurse=ARRAY/);
1011 # BugID 20010422.003
1015 'bool' => sub { return !$_[0]->is_zero() || undef; }
1021 return $self->{var} == 0;
1028 $self->{var} = shift;
1036 my $r = Foo->new(8);
1044 '""' => sub { return $_[0]->{var}; }
1051 $self->{var} = shift;
1058 my $utfvar = new utf8_o 200.2.1;
1059 is("$utfvar", 200.2.1); # 223 - stringify
1060 is("a$utfvar", "a".200.2.1); # 224 - overload via sv_2pv_flags
1062 # 225..227 -- more %{} tests. Hangs in 5.6.0, okay in later releases.
1063 # Basically this example implements strong encapsulation: if Hderef::import()
1064 # were to eval the overload code in the caller's namespace, the privatisation
1065 # would be quite transparent.
1067 use overload '%{}' => sub { (caller(0))[0] eq 'Foo' ? $_[0] : die "zap" };
1069 @Foo::ISA = 'Hderef';
1070 sub new { bless {}, shift }
1071 sub xet { @_ == 2 ? $_[0]->{$_[1]} :
1072 @_ == 3 ? ($_[0]->{$_[1]} = $_[2]) : undef }
1076 is ($a->xet('b'), 42);
1077 ok (!defined eval { $a->{b} });
1082 use overload '=' => sub { 42 },
1083 '++' => sub { my $x = ${$_[0]}; $_[0] };
1084 sub new { my $x = 42; bless \$x }
1088 local $SIG{__WARN__} = sub { $warn++ };
1097 my ($int, $out1, $out2);
1099 BEGIN { $int = 0; overload::constant 'integer' => sub {$int++; 17}; }
1103 is($int, 2, "#24313"); # 230
1104 is($out1, 17, "#24313"); # 231
1105 is($out2, 17, "#24313"); # 232
1110 use overload (qw(0+ numify fallback 1));
1117 sub numify { ${$_[0]} }
1122 use overload cmp => sub { 0 };
1123 package perl31793_fb;
1124 use overload cmp => sub { 0 }, fallback => 1;
1126 my $o = bless [], 'perl31793';
1127 my $of = bless [], 'perl31793_fb';
1128 my $no = bless [], 'no_overload';
1129 like(overload::StrVal(\"scalar"), qr/^SCALAR\(0x[0-9a-f]+\)$/);
1130 like(overload::StrVal([]), qr/^ARRAY\(0x[0-9a-f]+\)$/);
1131 like(overload::StrVal({}), qr/^HASH\(0x[0-9a-f]+\)$/);
1132 like(overload::StrVal(sub{1}), qr/^CODE\(0x[0-9a-f]+\)$/);
1133 like(overload::StrVal(\*GLOB), qr/^GLOB\(0x[0-9a-f]+\)$/);
1134 like(overload::StrVal(\$o), qr/^REF\(0x[0-9a-f]+\)$/);
1135 like(overload::StrVal(qr/a/), qr/^Regexp=REGEXP\(0x[0-9a-f]+\)$/);
1136 like(overload::StrVal($o), qr/^perl31793=ARRAY\(0x[0-9a-f]+\)$/);
1137 like(overload::StrVal($of), qr/^perl31793_fb=ARRAY\(0x[0-9a-f]+\)$/);
1138 like(overload::StrVal($no), qr/^no_overload=ARRAY\(0x[0-9a-f]+\)$/);
1141 # These are all check that overloaded values rather than reference addresses
1142 # are what is getting tested.
1143 my ($two, $one, $un, $deux) = map {new Numify $_} 2, 1, 1, 2;
1144 my ($ein, $zwei) = (1, 2);
1146 my %map = (one => 1, un => 1, ein => 1, deux => 2, two => 2, zwei => 2);
1147 foreach my $op (qw(<=> == != < <= > >=)) {
1148 foreach my $l (keys %map) {
1149 foreach my $r (keys %map) {
1150 my $ocode = "\$$l $op \$$r";
1151 my $rcode = "$map{$l} $op $map{$r}";
1153 my $got = eval $ocode;
1155 my $expect = eval $rcode;
1157 is ($got, $expect, $ocode) or print "# $rcode\n";
1162 # check that overloading works in regexes
1166 '""' => sub { "^$_[0][0]\$" },
1170 ? (ref $_[1] ? $_[1][0] : $_[1]) . ':' .$_[0][0]
1171 : $_[0][0] . ':' . (ref $_[1] ? $_[1][0] : $_[1])
1176 my $a = bless [ "a" ], 'Foo493';
1178 like('x:a', qr/x$a/);
1179 like('x:a:=', qr/x$a=$/);
1180 like('x:a:a:=', qr/x$a$a=$/);
1187 use overload qr => sub { qr/x/ }, fallback => 1;
1190 my $x = bless [], "QRonly";
1192 # like tries to be too clever, and decides that $x-stringified
1193 # doesn't look like a regex
1194 ok("x" =~ $x, "qr-only matches");
1195 ok("y" !~ $x, "qr-only doesn't match what it shouldn't");
1196 ok("xx" =~ /x$x/, "qr-only matches with concat");
1197 like("$x", qr/^QRonly=ARRAY/, "qr-only doesn't have string overload");
1199 my $qr = bless qr/y/, "QRonly";
1200 ok("x" =~ $qr, "qr with qr-overload uses overload");
1201 ok("y" !~ $qr, "qr with qr-overload uses overload");
1202 is("$qr", "".qr/y/, "qr with qr-overload stringify");
1205 ok("y" =~ $rx, "bare rx with qr-overload doesn't overload match");
1206 ok("x" !~ $rx, "bare rx with qr-overload doesn't overload match");
1207 is("$rx", "".qr/y/, "bare rx with qr-overload stringify");
1211 use overload qr => sub { qr/x/ }, q/""/ => sub { "y" };
1214 my $x = bless [], "QRandSTR";
1215 ok("x" =~ $x, "qr+str uses qr for match");
1216 ok("y" !~ $x, "qr+str uses qr for match");
1217 ok("xx" =~ /x$x/, "qr+str uses qr for match with concat");
1218 is("$x", "y", "qr+str uses str for stringify");
1220 my $qr = bless qr/z/, "QRandSTR";
1221 is("$qr", "y", "qr with qr+str uses str for stringify");
1222 ok("xx" =~ /x$x/, "qr with qr+str uses qr for match");
1225 ok("z" =~ $rx, "bare rx with qr+str doesn't overload match");
1226 is("$rx", "".qr/z/, "bare rx with qr+str doesn't overload stringify");
1230 use overload qr => sub { $_[0]->(@_) };
1233 use overload qr => sub { $_[0] };
1236 my $rx = bless sub { ${ qr/x/ } }, "QRany";
1237 ok("x" =~ $rx, "qr overload accepts a bare rx");
1238 ok("y" !~ $rx, "qr overload accepts a bare rx");
1240 my $str = bless sub { "x" }, "QRany";
1241 ok(!eval { "x" =~ $str }, "qr overload doesn't accept a string");
1242 like($@, qr/^Overloaded qr did not return a REGEXP/, "correct error");
1244 my $oqr = bless qr/z/, "QRandSTR";
1245 my $oqro = bless sub { $oqr }, "QRany";
1246 ok("z" =~ $oqro, "qr overload doesn't recurse");
1248 my $qrs = bless qr/z/, "QRself";
1249 ok("z" =~ $qrs, "qr overload can return self");
1253 use overload q/""/ => sub { "x" };
1256 use overload q/""/ => sub { "x" }, fallback => 1;
1259 my $fb = bless [], "STRonlyFB";
1260 ok("x" =~ $fb, "qr falls back to \"\"");
1261 ok("y" !~ $fb, "qr falls back to \"\"");
1263 my $nofb = bless [], "STRonly";
1264 ok("x" =~ $nofb, "qr falls back even without fallback");
1265 ok("y" !~ $nofb, "qr falls back even without fallback");
1270 my $twenty_three = 23;
1271 # Check that constant overloading propagates into evals
1272 BEGIN { overload::constant integer => sub { 23 } }
1273 is(eval "17", $twenty_three);
1279 bool => sub { shift->is_cool };
1282 $_[0]->{name} eq 'cool';
1287 bless $_[0], 'Brap';
1291 sub delete_with_self {
1294 bless $self, 'Brap';
1305 $obj = bless {name => 'cool'}, 'Sklorsh';
1307 ok(eval {if ($obj) {1}; 1}, $@ || 'reblessed into nonexistent namespace');
1309 $obj = bless {name => 'cool'}, 'Sklorsh';
1310 $obj->delete_with_self;
1311 ok (eval {if ($obj) {1}; 1}, $@);
1313 my $a = $b = {name => 'hot'};
1314 bless $b, 'Sklorsh';
1315 is(ref $a, 'Sklorsh');
1316 is(ref $b, 'Sklorsh');
1317 ok(!$b, "Expect overloaded boolean");
1318 ok(!$a, "Expect overloaded boolean");
1324 bool => sub { shift->{truth} eq 'yes' },
1325 '0+' => sub { shift->{truth} eq 'yes' ? '1' : '0' },
1326 '!' => sub { shift->{truth} eq 'no' },
1329 sub new { my $class = shift; bless { truth => shift }, $class }
1333 my $yes = Flrbbbbb->new('yes');
1335 $x = 1 if $yes; is($x, 1);
1336 $x = 2 unless $yes; is($x, 1);
1337 $x = 3 if !$yes; is($x, 1);
1338 $x = 4 unless !$yes; is($x, 4);
1340 my $no = Flrbbbbb->new('no');
1342 $x = 1 if $no; is($x, 0);
1343 $x = 2 unless $no; is($x, 2);
1344 $x = 3 if !$no; is($x, 3);
1345 $x = 4 unless !$no; is($x, 3);
1348 $x = 1 if !$no && $yes; is($x, 1);
1349 $x = 2 unless !$no && $yes; is($x, 1);
1350 $x = 3 if $no || !$yes; is($x, 1);
1351 $x = 4 unless $no || !$yes; is($x, 4);
1354 $x = 1 if !$no || !$yes; is($x, 1);
1355 $x = 2 unless !$no || !$yes; is($x, 1);
1356 $x = 3 if !$no && !$yes; is($x, 1);
1357 $x = 4 unless !$no && !$yes; is($x, 4);
1361 use Scalar::Util 'weaken';
1364 use overload '""' => sub {"CLiK KLAK"};
1371 $obj = bless do {my $a; \$a}, 'Shklitza';
1374 is ($obj, "CLiK KLAK");
1375 is ($ref, "CLiK KLAK");
1378 is ($ref, "CLiK KLAK");
1380 bless $obj, 'Ksshfwoom';
1382 like ($obj, qr/^Ksshfwoom=/);
1383 like ($ref, qr/^Ksshfwoom=/);
1391 # bit operations have overloadable assignment variants too
1393 sub new { bless \$_[1], $_[0] }
1396 "&=" => sub { bit->new($_[0]->val . ' & ' . $_[1]->val) },
1397 "^=" => sub { bit->new($_[0]->val . ' ^ ' . $_[1]->val) },
1398 "|" => sub { bit->new($_[0]->val . ' | ' . $_[1]->val) }, # |= by fallback
1401 sub val { ${$_[0]} }
1405 my $a = bit->new(my $va = 'a');
1406 my $b = bit->new(my $vb = 'b');
1409 is($a->val, 'a & b', "overloaded &= works");
1411 my $c = bit->new(my $vc = 'c');
1414 is($b->val, 'b ^ c', "overloaded ^= works");
1416 my $d = bit->new(my $vd = 'd');
1419 is($c->val, 'c | d', "overloaded |= (by fallback) works");
1423 # comparison operators with nomethod
1427 package nomethod_false;
1428 use overload nomethod => sub { $method = 'nomethod'; 0 };
1430 package nomethod_true;
1431 use overload nomethod => sub { $method= 'nomethod'; 'true' };
1435 local $SIG{__WARN__} = sub { $warning = $_[0] };
1437 my $f = bless [], 'nomethod_false';
1438 ($warning, $method) = ("", "");
1439 is($f eq 'whatever', 0, 'nomethod makes eq return 0');
1440 is($method, 'nomethod');
1442 my $t = bless [], 'nomethod_true';
1443 ($warning, $method) = ("", "");
1444 is($t eq 'whatever', 'true', 'nomethod makes eq return "true"');
1445 is($method, 'nomethod');
1446 is($warning, "", 'nomethod eq need not return number');
1449 package nomethod_false;
1450 use overload cmp => sub { $method = 'cmp'; 0 };
1452 $f = bless [], 'nomethod_false';
1453 ($warning, $method) = ("", "");
1454 ok($f eq 'whatever', 'eq falls back to cmp (nomethod not called)');
1458 package nomethod_true;
1459 use overload cmp => sub { $method = 'cmp'; 'true' };
1461 $t = bless [], 'nomethod_true';
1462 ($warning, $method) = ("", "");
1463 ok($t eq 'whatever', 'eq falls back to cmp (nomethod not called)');
1465 like($warning, qr/isn't numeric/, 'cmp should return number');
1470 # Subtle bug pre 5.10, as a side effect of the overloading flag being
1471 # stored on the reference rather than the referent. Despite the fact that
1472 # objects can only be accessed via references (even internally), the
1473 # referent actually knows that it's blessed, not the references. So taking
1474 # a new, unrelated, reference to it gives an object. However, the
1475 # overloading-or-not flag was on the reference prior to 5.10, and taking
1476 # a new reference didn't (use to) copy it.
1480 use overload '""' => sub {${$_[0]}};
1483 return "$_[0], $_[1]";
1490 my $crunch_eth = bless \$string, $class;
1492 is("$crunch_eth", $string);
1493 is ($crunch_eth->Pie("Meat"), "$string, Meat");
1495 my $wham_eth = \$string;
1497 is("$wham_eth", $string,
1498 'This reference did not have overloading in 5.8.8 and earlier');
1499 is ($crunch_eth->Pie("Apple"), "$string, Apple");
1501 my $class = ref $wham_eth;
1504 # Bless it back into its own class!
1505 bless $wham_eth, $class;
1507 is("$wham_eth", $string);
1508 is ($crunch_eth->Pie("Blackbird"), "$string, Blackbird");
1513 use overload "0+" => sub { $_[0][0] += 1; 42 };
1514 package numify_self;
1515 use overload "0+" => sub { $_[0][0]++; $_[0] };
1516 package numify_other;
1517 use overload "0+" => sub { $_[0][0]++; $_[0][1] = bless [], 'numify_int' };
1518 package numify_by_fallback;
1519 use overload fallback => 1;
1522 my $o = bless [], 'numify_int';
1523 is(int($o), 42, 'numifies to integer');
1524 is($o->[0], 1, 'int() numifies only once');
1527 my $num_val = int($aref);
1528 my $r = bless $aref, 'numify_self';
1529 is(int($r), $num_val, 'numifies to self');
1530 is($r->[0], 1, 'int() numifies once when returning self');
1532 my $s = bless [], 'numify_other';
1533 is(int($s), 42, 'numifies to numification of other object');
1534 is($s->[0], 1, 'int() numifies once when returning other object');
1535 is($s->[1][0], 1, 'returned object numifies too');
1537 my $m = bless $aref, 'numify_by_fallback';
1538 is(int($m), $num_val, 'numifies to usual reference value');
1539 is(abs($m), $num_val, 'numifies to usual reference value');
1540 is(-$m, -$num_val, 'numifies to usual reference value');
1541 is(0+$m, $num_val, 'numifies to usual reference value');
1542 is($m+0, $num_val, 'numifies to usual reference value');
1543 is($m+$m, 2*$num_val, 'numifies to usual reference value');
1544 is(0-$m, -$num_val, 'numifies to usual reference value');
1545 is(1*$m, $num_val, 'numifies to usual reference value');
1546 is($m/1, $num_val, 'numifies to usual reference value');
1547 is($m%100, $num_val%100, 'numifies to usual reference value');
1548 is($m**1, $num_val, 'numifies to usual reference value');
1550 is(abs($aref), $num_val, 'abs() of ref');
1551 is(-$aref, -$num_val, 'negative of ref');
1552 is(0+$aref, $num_val, 'ref addition');
1553 is($aref+0, $num_val, 'ref addition');
1554 is($aref+$aref, 2*$num_val, 'ref addition');
1555 is(0-$aref, -$num_val, 'subtraction of ref');
1556 is(1*$aref, $num_val, 'multiplicaton of ref');
1557 is($aref/1, $num_val, 'division of ref');
1558 is($aref%100, $num_val%100, 'modulo of ref');
1559 is($aref**1, $num_val, 'exponentiation of ref');
1563 package CopyConstructorFallback;
1565 '++' => sub { "$_[0]"; $_[0] },
1567 sub new { bless {} => shift }
1571 my $o = CopyConstructorFallback->new;
1572 my $x = $o++; # would segfault
1574 is($x, $o, "copy constructor falls back to assignment (postinc)");
1575 is($y, $o, "copy constructor falls back to assignment (preinc)");