9 use strict qw(refs subs);
13 # Test glob operations.
42 # Test fake references.
50 # Test real references.
57 # Test references to real arrays.
59 my $test = curr_test();
60 @ary = ($test,$test+1,$test+2,$test+3);
66 push(@{$ref[$i]}, "ok $ary[$i]\n");
77 # Test references to references.
81 is ($$$refref, 'Good');
83 # Test nested anonymous lists.
85 $ref = [[],2,[3,4,5,]];
88 is (${$$ref[2]}[2], 5);
89 is (scalar @{$$ref[0]}, 0);
92 is ($ref->[2]->[0], 3);
94 # Test references to hashes of references.
97 $refref->{"key"} = $ref;
98 is ($refref->{"key"}->[2]->[0], 3);
100 # Test to see if anonymous subarrays spring into existence.
102 $spring[5]->[0] = 123;
103 $spring[5]->[1] = 456;
104 push(@{$spring[5]}, 789);
105 is (join(':',@{$spring[5]}), "123:456:789");
107 # Test to see if anonymous subhashes spring into existence.
109 @{$spring2{"foo"}} = (1,2,3);
110 $spring2{"foo"}->[3] = 4;
111 is (join(':',@{$spring2{"foo"}}), "1:2:3:4");
113 # Test references to subroutines.
117 sub mysub { $called++; }
122 is ref eval {\&{""}}, "CODE", 'reference to &{""} [perl #94476]';
124 # Test references to return values of operators (TARGs/PADTMPs)
130 is join(" ", map $$_, @refs), "a b", 'refgen+PADTMP';
133 $subrefref = \\&mysub2;
134 is ($$subrefref->("GOOD"), "good");
135 sub mysub2 { lc shift }
137 # Test REGEXP assignment
140 skip_if_miniperl("no dynamic loading on miniperl, so can't load re", 5);
143 my $str = "$x"; # regex stringification may change
146 is ($y, $str, "bare REGEXP stringifies correctly");
147 ok (eval { "x" =~ $y }, "bare REGEXP matches correctly");
150 ok (re::is_regexp($z), "new ref to REXEXP passes is_regexp");
151 is ($z, $str, "new ref to REGEXP stringifies correctly");
152 ok (eval { "x" =~ $z }, "new ref to REGEXP matches correctly");
161 is ($x, $str, "REGEXP keeps a ref to its mother_re");
162 ok (eval { "x" =~ $x }, "REGEXP with mother_re still matches");
165 # Test the ref operator.
167 sub PVBM () { 'foo' }
168 { my $dummy = index 'foo', PVBM }
170 my $pviv = 1; "$pviv";
171 my $pvnv = 1.0; "$pvnv";
175 # tied lvalue => SCALAR, as we haven't tested tie yet
176 # BIND, 'cos we can't create them yet
177 # REGEXP, 'cos that requires overload or Scalar::Util
180 [ 'undef', SCALAR => \undef ],
181 [ 'constant IV', SCALAR => \1 ],
182 [ 'constant NV', SCALAR => \1.0 ],
183 [ 'constant PV', SCALAR => \'f' ],
184 [ 'scalar', SCALAR => \$x ],
185 [ 'PVIV', SCALAR => \$pviv ],
186 [ 'PVNV', SCALAR => \$pvnv ],
187 [ 'PVMG', SCALAR => \$0 ],
188 [ 'PVBM', SCALAR => \PVBM ],
189 [ 'scalar @array', SCALAR => \scalar @array ],
190 [ 'scalar %hash', SCALAR => \scalar %hash ],
191 [ 'vstring', VSTRING => \v1 ],
192 [ 'ref', REF => \\1 ],
193 [ 'substr lvalue', LVALUE => \substr($x, 0, 0) ],
194 [ 'pos lvalue', LVALUE => \pos ],
195 [ 'vec lvalue', LVALUE => \vec($x,0,1) ],
196 [ 'named array', ARRAY => \@ary ],
197 [ 'anon array', ARRAY => [ 1 ] ],
198 [ 'named hash', HASH => \%whatever ],
199 [ 'anon hash', HASH => { a => 1 } ],
200 [ 'named sub', CODE => \&mysub, ],
201 [ 'anon sub', CODE => sub { 1; } ],
202 [ 'glob', GLOB => \*foo ],
203 [ 'format', FORMAT => *STDERR{FORMAT} ],
205 my ($desc, $type, $ref) = @$_;
206 is (ref $ref, $type, "ref() for ref to $desc");
207 like ("$ref", qr/^$type\(0x[0-9a-f]+\)$/, "stringify for ref to $desc");
210 is (ref *STDOUT{IO}, 'IO::File', 'IO refs are blessed into IO::File');
211 like (*STDOUT{IO}, qr/^IO::File=IO\(0x[0-9a-f]+\)$/,
212 'stringify for IO refs');
214 { # Test re-use of ref's TARG [perl #101738]
215 my $obj = bless [], '____';
216 my $uniobj = bless [], chr 256;
217 my $get_ref = sub { ref shift };
218 my $dummy = &$get_ref($uniobj);
219 $dummy = &$get_ref($obj);
220 ok exists { ____ => undef }->{$dummy}, 'ref sets UTF8 flag correctly';
223 # Test anonymous hash syntax.
226 is (ref $anonhash, 'HASH');
227 $anonhash2 = {FOO => 'BAR', ABC => 'XYZ',};
228 is (join('', sort values %$anonhash2), 'BARXYZ');
230 # Test bless operator.
234 $object = bless $main'anonhash2;
235 main::is (ref $object, 'MYHASH');
236 main::is ($object->{ABC}, 'XYZ');
239 main::is (ref $object2, 'MYHASH');
241 # Test ordinary call on object method.
243 &mymethod($object,"argument");
246 local($THIS, @ARGS) = @_;
247 die 'Got a "' . ref($THIS). '" instead of a MYHASH'
248 unless ref $THIS eq 'MYHASH';
249 main::is ($ARGS[0], "argument");
250 main::is ($THIS->{FOO}, 'BAR');
253 # Test automatic destructor call.
258 $main'anonhash2 = "foo";
262 return unless $string;
263 main::is ($string, 'good');
265 # Test that the object has not already been "cursed".
266 main::isnt (ref shift, 'HASH');
269 # Now test inheritance of methods.
275 $main'object = bless {FOO => 'foo', BAR => 'bar'};
279 # Test arrow-style method invocation.
281 is ($object->doit("BAR"), 'bar');
283 # Test indirect-object-style method invocation.
285 $foo = doit $object "FOO";
286 main::is ($foo, 'foo');
290 die "Not an OBJ" unless ref $ref eq 'OBJ';
298 sub foo { main::is ($_[1], 'works') }
301 foo WHATEVER "works";
304 # test the \(@foo) construct
309 @baz = \(1,@foo,@bar);
310 is (scalar (@bar), 3);
311 is (scalar grep(ref($_), @bar), 3);
312 is (scalar (@baz), 3);
314 my(@fuu) = \(1..2,3);
316 my(@bzz) = \(1,@fuu,@baa);
317 is (scalar (@baa), 3);
318 is (scalar grep(ref($_), @baa), 3);
319 is (scalar (@bzz), 3);
321 # also, it can't be an lvalue
322 # (That’s what *you* think! --sprout)
323 eval '\\($x, $y) = (1, 2);';
324 like ($@, qr/Can\'t modify.*ref.*in.*assignment(?x:
325 )|Experimental aliasing via reference not enabled/);
327 # test for proper destruction of lexical objects
329 sub larry::DESTROY { print "# larry\nok $test\n"; }
330 sub curly::DESTROY { print "# curly\nok ", $test + 1, "\n"; }
331 sub moe::DESTROY { print "# moe\nok ", $test + 2, "\n"; }
334 my ($joe, @curly, %larry);
335 my $moe = bless \$joe, 'moe';
336 my $curly = bless \@curly, 'curly';
337 my $larry = bless \%larry, 'larry';
338 print "# leaving block\n";
341 print "# left block\n";
342 curr_test($test + 3);
348 { local(*bar) = "foo" }
358 # test if reblessing during destruction results in more destruction
362 sub new { bless {}, shift }
363 DESTROY { print "# destroying 'A'\nok ", $test + 1, "\n" }
365 sub new { bless {}, shift }
366 DESTROY { print "# destroying '_B'\nok $test\n"; bless shift, 'A' }
370 curr_test($test + 2);
372 # test if $_[0] is properly protected in DESTROY()
375 my $test = curr_test();
377 local $SIG{'__DIE__'} = sub {
380 print "# infinite recursion, bailing\nnot ok $test\n";
383 like ($m, qr/^Modification of a read-only/);
386 sub new { bless {}, shift }
387 DESTROY { $_[0] = 'foo' }
389 print "# should generate an error...\n";
392 print "# good, didn't recurse\n";
395 # test that DESTROY is called on all objects during global destruction,
396 # even those without hard references [perl #36347]
400 stderr => 1, prog => 'sub DESTROY { print qq-aaa\n- } bless \$a[0]'
402 "aaa\n", 'DESTROY called on array elem'
407 prog => '{ bless \my@x; *a=sub{@x}}sub DESTROY { print qq-aaa\n- }'
410 'DESTROY called on closure variable'
413 # But cursing objects must not result in double frees
414 # This caused "Attempt to free unreferenced scalar" in 5.16.
416 'bless \%foo::, bar::; bless \%bar::, foo::; print "ok\n"', "ok\n",
418 'no double free when stashes are blessed into each other');
421 # test if refgen behaves with autoviv magic
433 # This test is the reason for postponed destruction in sv_unref
438 # This test used to coredump. The BEGIN block is important as it causes the
439 # op that created the constant reference to be freed. Hence the only
440 # reference to the constant string "pass" is in $a. The hack that made
441 # sure $a = $a->[1] would work didn't work with references to constants.
444 foreach my $lexical ('', 'my $a; ') {
445 my $expect = "pass\n";
446 my $result = runperl (switches => ['-wl'], stderr => 1,
447 prog => $lexical . 'BEGIN {$a = \q{pass}}; $a = $$a; print $a');
450 is ($result, $expect);
454 sub x::DESTROY {print "ok ", $test + shift->[0], "\n"}
455 { my $a1 = bless [3],"x";
456 my $a2 = bless [2],"x";
457 { my $a3 = bless [1],"x";
458 my $a4 = bless [0],"x";
464 is (runperl (switches=>['-l'],
465 prog=> 'print 1; print qq-*$\*-;print 1;'),
470 runperl(prog => 'sub UNIVERSAL::AUTOLOAD { qr// } a->p' );
471 is ($?, 0, 'UNIVERSAL::AUTOLOAD called when freeing qr//');
473 runperl(prog => 'sub UNIVERSAL::DESTROY { warn } bless \$a, A', stderr => 1);
474 is ($?, 0, 'warn called inside UNIVERSAL::DESTROY');
479 runperl(prog => 'sub f { my $x = shift; *z = $x; } f({}); f();');
480 is ($?, 0, 'coredump on typeglob = (SvRV && !SvROK)');
482 # bug #27268: freeing self-referential typeglobs could trigger
483 # "Attempt to free unreferenced scalar" warnings
486 prog => 'use Symbol;my $x=bless \gensym,q{t}; print;*$$x=$x',
488 ), '', 'freeing self-referential typeglob');
490 # using a regex in the destructor for STDOUT segfaulted because the
491 # REGEX pad had already been freed (ithreads build only). The
492 # object is required to trigger the early freeing of GV refs to to STDOUT
495 local $TODO = "works but output through pipe is mangled" if $^O eq 'VMS';
497 prog => '$x=bless[]; sub IO::Handle::DESTROY{$_=q{bad};s/bad/ok/;print}',
499 ), qr/^(ok)+$/, 'STDOUT destructor');
505 $name_utf8 = $name8 . chr 256;
508 is ($$name8, undef, 'Nothing before we start');
509 is ($$name_utf8, undef, 'Nothing before we start');
511 is ($$name8, "Pound", 'Accessing via 8 bit symref works');
512 is ($$name_utf8, "Pound", 'Accessing via UTF8 symref works');
517 $name_utf8 = $name = chr 9787;
518 utf8::encode $name_utf8;
520 is (length $name, 1, "Name is 1 char");
521 is (length $name_utf8, 3, "UTF8 representation is 3 chars");
523 is ($$name, undef, 'Nothing before we start');
524 is ($$name_utf8, undef, 'Nothing before we start');
526 is ($$name, "Face", 'Accessing via Unicode symref works');
527 is ($$name_utf8, undef,
528 'Accessing via the UTF8 byte sequence gives nothing');
536 isnt ($name1, $name2, "They differ");
538 is ($$name1, undef, 'Nothing before we start (scalars)');
539 is ($$name2, undef, 'Nothing before we start');
541 is ($$name1, "Yummy", 'Accessing via the correct name works');
543 'Accessing via a different NUL-containing name gives nothing');
544 # defined uses a different code path
545 ok (defined $$name1, 'defined via the correct name works');
546 ok (!defined $$name2,
547 'defined via a different NUL-containing name gives nothing');
549 is ($name1->[0], undef, 'Nothing before we start (arrays)');
550 is ($name2->[0], undef, 'Nothing before we start');
551 $name1->[0] = "Yummy";
552 is ($name1->[0], "Yummy", 'Accessing via the correct name works');
553 is ($name2->[0], undef,
554 'Accessing via a different NUL-containing name gives nothing');
555 ok (defined $name1->[0], 'defined via the correct name works');
556 ok (!defined$name2->[0],
557 'defined via a different NUL-containing name gives nothing');
559 my (undef, $one) = @{$name1}[2,3];
560 my (undef, $two) = @{$name2}[2,3];
561 is ($one, undef, 'Nothing before we start (array slices)');
562 is ($two, undef, 'Nothing before we start');
563 @{$name1}[2,3] = ("Very", "Yummy");
564 (undef, $one) = @{$name1}[2,3];
565 (undef, $two) = @{$name2}[2,3];
566 is ($one, "Yummy", 'Accessing via the correct name works');
568 'Accessing via a different NUL-containing name gives nothing');
569 ok (defined $one, 'defined via the correct name works');
571 'defined via a different NUL-containing name gives nothing');
573 is ($name1->{PWOF}, undef, 'Nothing before we start (hashes)');
574 is ($name2->{PWOF}, undef, 'Nothing before we start');
575 $name1->{PWOF} = "Yummy";
576 is ($name1->{PWOF}, "Yummy", 'Accessing via the correct name works');
577 is ($name2->{PWOF}, undef,
578 'Accessing via a different NUL-containing name gives nothing');
579 ok (defined $name1->{PWOF}, 'defined via the correct name works');
580 ok (!defined $name2->{PWOF},
581 'defined via a different NUL-containing name gives nothing');
583 my (undef, $one) = @{$name1}{'SNIF', 'BEEYOOP'};
584 my (undef, $two) = @{$name2}{'SNIF', 'BEEYOOP'};
585 is ($one, undef, 'Nothing before we start (hash slices)');
586 is ($two, undef, 'Nothing before we start');
587 @{$name1}{'SNIF', 'BEEYOOP'} = ("Very", "Yummy");
588 (undef, $one) = @{$name1}{'SNIF', 'BEEYOOP'};
589 (undef, $two) = @{$name2}{'SNIF', 'BEEYOOP'};
590 is ($one, "Yummy", 'Accessing via the correct name works');
592 'Accessing via a different NUL-containing name gives nothing');
593 ok (defined $one, 'defined via the correct name works');
595 'defined via a different NUL-containing name gives nothing');
597 $name1 = "Left"; $name2 = "Left\0Right";
598 my $glob2 = *{$name2};
600 is ($glob1, undef, "We get different typeglobs. In fact, undef");
602 *{$name1} = sub {"One"};
603 *{$name2} = sub {"Two"};
605 is (&{$name1}, "One");
606 is (&{$name2}, "Two");
609 # test derefs after list slice
611 is ( ({foo => "bar"})[0]{foo}, "bar", 'hash deref from list slice w/o ->' );
612 is ( ({foo => "bar"})[0]->{foo}, "bar", 'hash deref from list slice w/ ->' );
613 is ( ([qw/foo bar/])[0][1], "bar", 'array deref from list slice w/o ->' );
614 is ( ([qw/foo bar/])[0]->[1], "bar", 'array deref from list slice w/ ->' );
615 is ( (sub {"bar"})[0](), "bar", 'code deref from list slice w/o ->' );
616 is ( (sub {"bar"})[0]->(), "bar", 'code deref from list slice w/ ->' );
618 # deref on empty list shouldn't autovivify
622 like ( "$@", qr/Can't use an undefined value as a HASH reference/,
623 "deref of undef from list slice fails" );
626 # test dereferencing errors
631 foreach $ref (*STDOUT{IO}, *STDERR{FORMAT}) {
633 like($@, qr/Not a SCALAR reference/, "Scalar dereference");
635 like($@, qr/Not an ARRAY reference/, "Array dereference");
637 like($@, qr/Not a HASH reference/, "Hash dereference");
639 like($@, qr/Not a CODE reference/, "Code dereference");
642 $ref = *STDERR{FORMAT};
644 like($@, qr/Not a GLOB reference/, "Glob dereference");
648 is($@, '', "Glob dereference of PVIO is acceptable");
650 is($ref, *{$ref}{IO}, "IO slot of the temporary glob is set correctly");
653 # these will segfault if they fail
658 ok (!eval { *$rpvbm }, 'PVBM ref is not a GLOB ref');
659 ok (!eval { *$pvbm }, 'PVBM is not a GLOB ref');
660 ok (!eval { $$pvbm }, 'PVBM is not a SCALAR ref');
661 ok (!eval { @$pvbm }, 'PVBM is not an ARRAY ref');
662 ok (!eval { %$pvbm }, 'PVBM is not a HASH ref');
663 ok (!eval { $pvbm->() }, 'PVBM is not a CODE ref');
664 ok (!eval { $rpvbm->foo }, 'PVBM is not an object');
667 is( runperl(stderr => 1, prog => 'map eval qq(exit),1 for 1'), "");
668 is( runperl(stderr => 1, prog => 'eval { for (1) { map { die } 2 } };'), "");
669 is( runperl(stderr => 1, prog => 'for (125) { map { exit } (213)}'), "");
670 my $hushed = $^O eq 'VMS' ? 'use vmsish qw(hushed);' : '';
671 is( runperl(stderr => 1, prog => $hushed . 'map die,4 for 3'), "Died at -e line 1.\n");
672 is( runperl(stderr => 1, prog => $hushed . 'grep die,4 for 3'), "Died at -e line 1.\n");
673 is( runperl(stderr => 1, prog => $hushed . 'for $a (3) {@b=sort {die} 4,5}'), "Died at -e line 1.\n");
676 is( runperl(stderr => 1, prog => 'my $i;for $i (1) { for $i (2) { } }'), "");
678 # The mechanism for freeing objects in globs used to leave dangling
679 # pointers to freed SVs. To test this, we construct this nested structure:
680 # GV => blessed(AV) => RV => GV => blessed(SV)
681 # all with a refcnt of 1, and hope that the second GV gets processed first
682 # by do_clean_named_objs. Then when the first GV is processed, it mustn't
683 # find anything nasty left by the previous GV processing.
684 # The eval is stop things in the main body of the code holding a reference
685 # to a GV, and the print at the end seems to bee necessary to ensure
686 # the correct freeing order of *x and *y (no, I don't know why - DAPM).
689 prog => 'eval q[bless \@y; bless \$x; $y[0] = \*x; $z = \*y; ]; '
690 . 'delete $::{x}; delete $::{y}; print qq{ok\n};',
692 "ok\n", 'freeing freed glob in global destruction');
695 # Test undefined hash references as arguments to %{} in boolean context
699 eval { my $foo; %$foo; }; ok !$@, '%$undef';
700 eval { my $foo; scalar %$foo; }; ok !$@, 'scalar %$undef';
701 eval { my $foo; !%$foo; }; ok !$@, '!%$undef';
702 eval { my $foo; if ( %$foo) {} }; ok !$@, 'if ( %$undef) {}';
703 eval { my $foo; if (!%$foo) {} }; ok !$@, 'if (!%$undef) {}';
704 eval { my $foo; unless ( %$foo) {} }; ok !$@, 'unless ( %$undef) {}';
705 eval { my $foo; unless (!%$foo) {} }; ok !$@, 'unless (!%$undef) {}';
706 eval { my $foo; 1 if %$foo; }; ok !$@, '1 if %$undef';
707 eval { my $foo; 1 if !%$foo; }; ok !$@, '1 if !%$undef';
708 eval { my $foo; 1 unless %$foo; }; ok !$@, '1 unless %$undef;';
709 eval { my $foo; 1 unless ! %$foo; }; ok !$@, '1 unless ! %$undef';
710 eval { my $foo; %$foo ? 1 : 0; }; ok !$@, ' %$undef ? 1 : 0';
711 eval { my $foo; !%$foo ? 1 : 0; }; ok !$@, '!%$undef ? 1 : 0';
715 # Make sure that a leaked thinggy with multiple weak references to
716 # it doesn't trigger a panic with multiple rounds of global cleanup
717 # (Perl_sv_clean_all).
720 skip_if_miniperl('no Scalar::Util under miniperl', 4);
722 local $ENV{PERL_DESTRUCT_LEVEL} = 2;
724 # we do all permutations of array/hash, 1ref/2ref, to account
725 # for the different way backref magic is stored
727 fresh_perl_is(<<'EOF', 'ok', { stderr => 1 }, 'array with 1 weak ref');
728 use Scalar::Util qw(weaken);
730 Internals::SvREFCNT(@$r, 9);
736 fresh_perl_is(<<'EOF', 'ok', { stderr => 1 }, 'array with 2 weak refs');
737 use Scalar::Util qw(weaken);
739 Internals::SvREFCNT(@$r, 9);
747 fresh_perl_is(<<'EOF', 'ok', { stderr => 1 }, 'hash with 1 weak ref');
748 use Scalar::Util qw(weaken);
750 Internals::SvREFCNT(%$r, 9);
756 fresh_perl_is(<<'EOF', 'ok', { stderr => 1 }, 'hash with 2 weak refs');
757 use Scalar::Util qw(weaken);
759 Internals::SvREFCNT(%$r, 9);
770 skip_if_miniperl "no Scalar::Util on miniperl", 1;
772 *hassgropper::DESTROY = sub {
773 require Scalar::Util;
774 eval { Scalar::Util::weaken($_[0]) };
776 # This line caused a crash before weaken refused to weaken a
777 # read-only reference:
778 $do::not::overwrite::this = $_[0];
780 my $xs = bless [], "hassgropper";
782 like $error, qr/^Modification of a read-only/,
783 'weaken refuses to weaken a read-only ref';
784 # Now that the test has passed, avoid sabotaging global destruction:
785 undef *hassgropper::DESTROY;
786 undef $do::not::overwrite::this;
790 is ref( bless {}, "nul\0clean" ), "nul\0clean", "ref() is nul-clean";
792 # Test constants and references thereto.
795 like $@, qr/^Modification of a read-only/,
796 'assignment to value aliased to literal number';
799 like $@, qr/^Modification of a read-only/,
800 'refgen does not allow assignment to value aliased to literal number';
802 for ("4eounthouonth") {
804 like $@, qr/^Modification of a read-only/,
805 'assignment to value aliased to literal string';
808 like $@, qr/^Modification of a read-only/,
809 'refgen does not allow assignment to value aliased to literal string';
814 '[perl #109746] referential identity of \literal under threads+mad'
817 # Bit of a hack to make test.pl happy. There are 3 more tests after it leaves.
819 curr_test($test + 3);
820 # test global destruction
822 my $test1 = $test + 1;
823 my $test2 = $test + 2;
828 $ref3 = bless ["ok $test2\n"]; # package destruction
829 my $ref2 = bless ["ok $test1\n"]; # lexical destruction
830 local $ref1 = bless ["ok $test\n"]; # dynamic destruction
831 1; # flush any temp values on stack