xref: /openbsd-src/gnu/usr.bin/perl/t/op/tie.t (revision e068048151d29f2562a32185e21a8ba885482260)
1#!./perl
2
3# Add new tests to the end with format:
4# ########
5#
6# # test description
7# Test code
8# EXPECT
9# Warn or die msgs (if any) at - line 1234
10#
11
12chdir 't' if -d 't';
13require './test.pl';
14set_up_inc('../lib');
15
16$|=1;
17
18run_multiple_progs('', \*DATA);
19
20done_testing();
21
22__END__
23
24# standard behaviour, without any extra references
25use Tie::Hash ;
26tie %h, Tie::StdHash;
27untie %h;
28EXPECT
29########
30# SKIP ?!defined &DynaLoader::boot_DynaLoader && !eval 'require base'
31# (skip under miniperl if base.pm is not in lib/ yet)
32
33# standard behaviour, without any extra references
34use Tie::Hash ;
35{package Tie::HashUntie;
36 use base 'Tie::StdHash';
37 sub UNTIE
38  {
39   warn "Untied\n";
40  }
41}
42tie %h, Tie::HashUntie;
43untie %h;
44EXPECT
45Untied
46########
47
48# standard behaviour, with 1 extra reference
49use Tie::Hash ;
50$a = tie %h, Tie::StdHash;
51untie %h;
52EXPECT
53########
54
55# standard behaviour, with 1 extra reference via tied
56use Tie::Hash ;
57tie %h, Tie::StdHash;
58$a = tied %h;
59untie %h;
60EXPECT
61########
62
63# standard behaviour, with 1 extra reference which is destroyed
64use Tie::Hash ;
65$a = tie %h, Tie::StdHash;
66$a = 0 ;
67untie %h;
68EXPECT
69########
70
71# standard behaviour, with 1 extra reference via tied which is destroyed
72use Tie::Hash ;
73tie %h, Tie::StdHash;
74$a = tied %h;
75$a = 0 ;
76untie %h;
77EXPECT
78########
79
80# strict behaviour, without any extra references
81use warnings 'untie';
82use Tie::Hash ;
83tie %h, Tie::StdHash;
84untie %h;
85EXPECT
86########
87
88# strict behaviour, with 1 extra references generating an error
89use warnings 'untie';
90use Tie::Hash ;
91$a = tie %h, Tie::StdHash;
92untie %h;
93EXPECT
94untie attempted while 1 inner references still exist at - line 6.
95########
96
97# strict behaviour, with 1 extra references via tied generating an error
98use warnings 'untie';
99use Tie::Hash ;
100tie %h, Tie::StdHash;
101$a = tied %h;
102untie %h;
103EXPECT
104untie attempted while 1 inner references still exist at - line 7.
105########
106
107# strict behaviour, with 1 extra references which are destroyed
108use warnings 'untie';
109use Tie::Hash ;
110$a = tie %h, Tie::StdHash;
111$a = 0 ;
112untie %h;
113EXPECT
114########
115
116# strict behaviour, with extra 1 references via tied which are destroyed
117use warnings 'untie';
118use Tie::Hash ;
119tie %h, Tie::StdHash;
120$a = tied %h;
121$a = 0 ;
122untie %h;
123EXPECT
124########
125
126# strict error behaviour, with 2 extra references
127use warnings 'untie';
128use Tie::Hash ;
129$a = tie %h, Tie::StdHash;
130$b = tied %h ;
131untie %h;
132EXPECT
133untie attempted while 2 inner references still exist at - line 7.
134########
135
136# strict behaviour, check scope of strictness.
137no warnings 'untie';
138use Tie::Hash ;
139$A = tie %H, Tie::StdHash;
140$C = $B = tied %H ;
141{
142    use warnings 'untie';
143    use Tie::Hash ;
144    tie %h, Tie::StdHash;
145    untie %h;
146}
147untie %H;
148EXPECT
149########
150
151# Forbidden aggregate self-ties
152sub Self::TIEHASH { bless $_[1], $_[0] }
153{
154    my %c;
155    tie %c, 'Self', \%c;
156}
157EXPECT
158Self-ties of arrays and hashes are not supported at - line 6.
159########
160
161# Allowed scalar self-ties
162my $destroyed = 0;
163sub Self::TIESCALAR { bless $_[1], $_[0] }
164sub Self::DESTROY   { $destroyed = 1; }
165{
166    my $c = 42;
167    tie $c, 'Self', \$c;
168}
169die "self-tied scalar not DESTROYed" unless $destroyed == 1;
170EXPECT
171########
172
173# Allowed glob self-ties
174my $destroyed = 0;
175my $printed   = 0;
176sub Self2::TIEHANDLE { bless $_[1], $_[0] }
177sub Self2::DESTROY   { $destroyed = 1; }
178sub Self2::PRINT     { $printed = 1; }
179{
180    use Symbol;
181    my $c = gensym;
182    tie *$c, 'Self2', $c;
183    print $c 'Hello';
184}
185die "self-tied glob not PRINTed" unless $printed == 1;
186die "self-tied glob not DESTROYed" unless $destroyed == 1;
187EXPECT
188########
189
190# Allowed IO self-ties
191my $destroyed = 0;
192sub Self3::TIEHANDLE { bless $_[1], $_[0] }
193sub Self3::DESTROY   { $destroyed = 1; }
194sub Self3::PRINT     { $printed = 1; }
195{
196    use Symbol 'geniosym';
197    my $c = geniosym;
198    tie *$c, 'Self3', $c;
199    print $c 'Hello';
200}
201die "self-tied IO not PRINTed" unless $printed == 1;
202die "self-tied IO not DESTROYed" unless $destroyed == 1;
203EXPECT
204########
205
206# TODO IO "self-tie" via TEMP glob
207my $destroyed = 0;
208sub Self3::TIEHANDLE { bless $_[1], $_[0] }
209sub Self3::DESTROY   { $destroyed = 1; }
210sub Self3::PRINT     { $printed = 1; }
211{
212    use Symbol 'geniosym';
213    my $c = geniosym;
214    tie *$c, 'Self3', \*$c;
215    print $c 'Hello';
216}
217die "IO tied to TEMP glob not PRINTed" unless $printed == 1;
218die "IO tied to TEMP glob not DESTROYed" unless $destroyed == 1;
219EXPECT
220########
221
222# Interaction of tie and vec
223
224my ($a, $b);
225use Tie::Scalar;
226tie $a,Tie::StdScalar or die;
227vec($b,1,1)=1;
228$a = $b;
229vec($a,1,1)=0;
230vec($b,1,1)=0;
231die unless $a eq $b;
232EXPECT
233########
234
235# correct unlocalisation of tied hashes (patch #16431)
236use Tie::Hash ;
237tie %tied, Tie::StdHash;
238{ local $hash{'foo'} } warn "plain hash bad unlocalize" if exists $hash{'foo'};
239{ local $tied{'foo'} } warn "tied hash bad unlocalize" if exists $tied{'foo'};
240{ local $ENV{'foo'}  } warn "%ENV bad unlocalize" if exists $ENV{'foo'};
241EXPECT
242########
243
244# An attempt at lvalueable barewords broke this
245tie FH, 'main';
246EXPECT
247Can't modify constant item in tie at - line 3, near "'main';"
248Execution of - aborted due to compilation errors.
249########
250
251# localizing tied hash slices
252$ENV{FooA} = 1;
253$ENV{FooB} = 2;
254print exists $ENV{FooA} ? 1 : 0, "\n";
255print exists $ENV{FooB} ? 2 : 0, "\n";
256print exists $ENV{FooC} ? 3 : 0, "\n";
257{
258    local @ENV{qw(FooA FooC)};
259    print exists $ENV{FooA} ? 4 : 0, "\n";
260    print exists $ENV{FooB} ? 5 : 0, "\n";
261    print exists $ENV{FooC} ? 6 : 0, "\n";
262}
263print exists $ENV{FooA} ? 7 : 0, "\n";
264print exists $ENV{FooB} ? 8 : 0, "\n";
265print exists $ENV{FooC} ? 9 : 0, "\n"; # this should not exist
266EXPECT
2671
2682
2690
2704
2715
2726
2737
2748
2750
276########
277#
278# FETCH freeing tie'd SV still works
279sub TIESCALAR { bless [] }
280sub FETCH { *a = \1; 2 }
281tie $a, 'main';
282print $a;
283EXPECT
2842
285########
286
287#  [20020716.007 (#10080)] - nested FETCHES
288
289sub F1::TIEARRAY { bless [], 'F1' }
290sub F1::FETCH { 1 }
291my @f1;
292tie @f1, 'F1';
293
294sub F2::TIEARRAY { bless [2], 'F2' }
295sub F2::FETCH { my $self = shift; my $x = $f1[3]; $self }
296my @f2;
297tie @f2, 'F2';
298
299print $f2[4][0],"\n";
300
301sub F3::TIEHASH { bless [], 'F3' }
302sub F3::FETCH { 1 }
303my %f3;
304tie %f3, 'F3';
305
306sub F4::TIEHASH { bless [3], 'F4' }
307sub F4::FETCH { my $self = shift; my $x = $f3{3}; $self }
308my %f4;
309tie %f4, 'F4';
310
311print $f4{'foo'}[0],"\n";
312
313EXPECT
3142
3153
316########
317# test untie() from within FETCH
318package Foo;
319sub TIESCALAR { my $pkg = shift; return bless [@_], $pkg; }
320sub FETCH {
321  my $self = shift;
322  my ($obj, $field) = @$self;
323  untie $obj->{$field};
324  $obj->{$field} = "Bar";
325}
326package main;
327tie $a->{foo}, "Foo", $a, "foo";
328my $s = $a->{foo}; # access once
329# the hash element should not be tied anymore
330print defined tied $a->{foo} ? "not ok" : "ok";
331EXPECT
332ok
333########
334# the tmps returned by FETCH should appear to be SCALAR
335# (even though they are now implemented using PVLVs.)
336package X;
337sub TIEHASH { bless {} }
338sub TIEARRAY { bless {} }
339sub FETCH {1}
340my (%h, @a);
341tie %h, 'X';
342tie @a, 'X';
343my $r1 = \$h{1};
344my $r2 = \$a[0];
345my $s = "$r1 ". ref($r1) . " $r2 " . ref($r2);
346$s=~ s/\(0x\w+\)//g;
347print $s, "\n";
348EXPECT
349SCALAR SCALAR SCALAR SCALAR
350########
351# [perl #23287] segfault in untie
352sub TIESCALAR { bless $_[1], $_[0] }
353my $var;
354tie $var, 'main', \$var;
355untie $var;
356EXPECT
357########
358# Test case from perlmonks by runrig
359# http://www.perlmonks.org/index.pl?node_id=273490
360# "Here is what I tried. I think its similar to what you've tried
361#  above. Its odd but convenient that after untie'ing you are left with
362#  a variable that has the same value as was last returned from
363#  FETCH. (At least on my perl v5.6.1). So you don't need to pass a
364#  reference to the variable in order to set it after the untie (here it
365#  is accessed through a closure)."
366use strict;
367use warnings;
368package MyTied;
369sub TIESCALAR {
370    my ($class,$code) = @_;
371    bless $code, $class;
372}
373sub FETCH {
374    my $self = shift;
375    print "Untie\n";
376    $self->();
377}
378package main;
379my $var;
380tie $var, 'MyTied', sub { untie $var; 4 };
381print "One\n";
382print "$var\n";
383print "Two\n";
384print "$var\n";
385print "Three\n";
386print "$var\n";
387EXPECT
388One
389Untie
3904
391Two
3924
393Three
3944
395########
396# [perl #22297] cannot untie scalar from within tied FETCH
397my $counter = 0;
398my $x = 7;
399my $ref = \$x;
400tie $x, 'Overlay', $ref, $x;
401my $y;
402$y = $x;
403$y = $x;
404$y = $x;
405$y = $x;
406#print "WILL EXTERNAL UNTIE $ref\n";
407untie $$ref;
408$y = $x;
409$y = $x;
410$y = $x;
411$y = $x;
412#print "counter = $counter\n";
413
414print (($counter == 1) ? "ok\n" : "not ok\n");
415
416package Overlay;
417
418sub TIESCALAR
419{
420        my $pkg = shift;
421        my ($ref, $val) = @_;
422        return bless [ $ref, $val ], $pkg;
423}
424
425sub FETCH
426{
427        my $self = shift;
428        my ($ref, $val) = @$self;
429        #print "WILL INTERNAL UNITE $ref\n";
430        $counter++;
431        untie $$ref;
432        return $val;
433}
434EXPECT
435ok
436########
437
438# [perl #948] cannot meaningfully tie $,
439package TieDollarComma;
440
441sub TIESCALAR {
442     my $pkg = shift;
443     return bless \my $x, $pkg;
444}
445
446sub STORE {
447    my $self = shift;
448    $$self = shift;
449    print "STORE set '$$self'\n";
450}
451
452sub FETCH {
453    my $self = shift;
454    print "<FETCH>";
455    return $$self;
456}
457package main;
458
459tie $,, 'TieDollarComma';
460$, = 'BOBBINS';
461print "join", "things", "up\n";
462EXPECT
463STORE set 'BOBBINS'
464join<FETCH>BOBBINSthings<FETCH>BOBBINSup
465########
466
467# test SCALAR method
468package TieScalar;
469
470sub TIEHASH {
471    my $pkg = shift;
472    bless { } => $pkg;
473}
474
475sub STORE {
476    $_[0]->{$_[1]} = $_[2];
477}
478
479sub FETCH {
480    $_[0]->{$_[1]}
481}
482
483sub CLEAR {
484    %{ $_[0] } = ();
485}
486
487sub SCALAR {
488    print "SCALAR\n";
489    return 0 if ! keys %{$_[0]};
490    sprintf "%i/%i", scalar keys %{$_[0]}, scalar keys %{$_[0]};
491}
492
493package main;
494tie my %h => "TieScalar";
495$h{key1} = "val1";
496$h{key2} = "val2";
497print scalar %h, "\n"
498    if %h; # this should also call SCALAR but implicitly
499%h = ();
500print scalar %h, "\n"
501    if !%h; # this should also call SCALAR but implicitly
502EXPECT
503SCALAR
504SCALAR
5052/2
506SCALAR
507SCALAR
5080
509########
510
511# test scalar on tied hash when no SCALAR method has been given
512package TieScalar;
513
514sub TIEHASH {
515    my $pkg = shift;
516    bless { } => $pkg;
517}
518sub STORE {
519    $_[0]->{$_[1]} = $_[2];
520}
521sub FETCH {
522    $_[0]->{$_[1]}
523}
524sub CLEAR {
525    %{ $_[0] } = ();
526}
527sub FIRSTKEY {
528    my $a = keys %{ $_[0] };
529    print "FIRSTKEY\n";
530    each %{ $_[0] };
531}
532
533package main;
534tie my %h => "TieScalar";
535
536if (!%h) {
537    print "empty\n";
538} else {
539    print "not empty\n";
540}
541
542$h{key1} = "val1";
543print "not empty\n" if %h;
544print "not empty\n" if %h;
545print "-->\n";
546my ($k,$v) = each %h;
547print "<--\n";
548print "not empty\n" if %h;
549%h = ();
550print "empty\n" if ! %h;
551EXPECT
552FIRSTKEY
553empty
554FIRSTKEY
555not empty
556FIRSTKEY
557not empty
558-->
559FIRSTKEY
560<--
561not empty
562FIRSTKEY
563empty
564########
565sub TIESCALAR { bless {} }
566sub FETCH { my $x = 3.3; 1 if 0+$x; $x }
567tie $h, "main";
568print $h,"\n";
569EXPECT
5703.3
571########
572sub TIESCALAR { bless {} }
573sub FETCH { shift()->{i} ++ }
574tie $h, "main";
575print $h.$h;
576EXPECT
57701
578########
579# SKIP ? $IS_EBCDIC
580# skipped on EBCDIC because "2" | "8" is 0xFA (not COLON as it is on ASCII),
581# which isn't representable in this file's UTF-8 encoding.
582# Bug 53482 (and maybe others)
583
584sub TIESCALAR { my $foo = $_[1]; bless \$foo, $_[0] }
585sub FETCH { ${$_[0]} }
586tie my $x1, "main", 2;
587tie my $y1, "main", 8;
588print $x1 | $y1;
589print $x1 | $y1;
590tie my $x2, "main", "2";
591tie my $y2, "main", "8";
592print $x2 | $y2;
593print $x2 | $y2;
594EXPECT
5951010::
596########
597# Bug 36267
598sub TIEHASH  { bless {}, $_[0] }
599sub STORE    { $_[0]->{$_[1]} = $_[2] }
600sub FIRSTKEY { my $a = scalar keys %{$_[0]}; each %{$_[0]} }
601sub NEXTKEY  { each %{$_[0]} }
602sub DELETE   { delete $_[0]->{$_[1]} }
603sub CLEAR    { %{$_[0]} = () }
604$h{b}=1;
605delete $h{b};
606print scalar keys %h, "\n";
607tie %h, 'main';
608$i{a}=1;
609%h = %i;
610untie %h;
611print scalar keys %h, "\n";
612EXPECT
6130
6140
615########
616# Bug 37731
617sub foo::TIESCALAR { bless {value => $_[1]}, $_[0] }
618sub foo::FETCH { $_[0]->{value} }
619tie my $VAR, 'foo', '42';
620foreach my $var ($VAR) {
621    print +($var eq $VAR) ? "yes\n" : "no\n";
622}
623EXPECT
624yes
625########
626sub TIEARRAY { bless [], 'main' }
627{
628    local @a;
629    tie @a, 'main';
630}
631print "tied\n" if tied @a;
632EXPECT
633########
634sub TIEHASH { bless [], 'main' }
635{
636    local %h;
637    tie %h, 'main';
638}
639print "tied\n" if tied %h;
640EXPECT
641########
642# RT 20727: PL_defoutgv is left as a tied element
643sub TIESCALAR { return bless {}, 'main' }
644
645sub STORE {
646    select($_[1]);
647    $_[1] = 1;
648    select(); # this used to coredump or assert fail
649}
650tie $SELECT, 'main';
651$SELECT = *STDERR;
652EXPECT
653########
654# RT 23810: eval in die in FETCH can corrupt context stack
655
656my $file = 'rt23810.pm';
657
658my $e;
659my $s;
660
661sub do_require {
662    my ($str, $eval) = @_;
663    open my $fh, '>', $file or die "Can't create $file: $!\n";
664    print $fh $str;
665    close $fh;
666    if ($eval) {
667	$s .= '-ERQ';
668	eval { require $pm; $s .= '-ENDE' }
669    }
670    else {
671	$s .= '-RQ';
672	require $pm;
673    }
674    $s .= '-ENDRQ';
675    unlink $file;
676}
677
678sub TIEHASH { bless {} }
679
680sub FETCH {
681    # 10 or more syntax errors makes yyparse croak()
682    my $bad = q{$x+;$x+;$x+;$x+;$x+;$x+;$x+;$x+;$x+$x+;$x+;$x+;$x+;$x+;;$x+;};
683
684    if ($_[1] eq 'eval') {
685	$s .= 'EVAL';
686	eval q[BEGIN { die; $s .= '-X1' }];
687	$s .= '-BD';
688	eval q[BEGIN { $x+ }];
689	$s .= '-BS';
690	eval '$x+';
691	$s .= '-E1';
692	$s .= '-S1' while $@ =~ /syntax error at/g;
693	eval $bad;
694	$s .= '-E2';
695	$s .= '-S2' while $@ =~ /syntax error at/g;
696    }
697    elsif ($_[1] eq 'require') {
698	$s .= 'REQUIRE';
699	my @text = (
700	    q[BEGIN { die; $s .= '-X1' }],
701	    q[BEGIN { $x+ }],
702	    '$x+',
703	    $bad
704	);
705	for my $i (0..$#text) {
706	    $s .= "-$i";
707	    do_require($txt[$i], 0) if $e;;
708	    do_require($txt[$i], 1);
709	}
710    }
711    elsif ($_[1] eq 'exit') {
712	eval q[exit(0); print "overshot eval\n"];
713    }
714    else {
715	print "unknown key: '$_[1]'\n";
716    }
717    return "-R";
718}
719my %foo;
720tie %foo, "main";
721
722for my $action(qw(eval require)) {
723    $s = ''; $e = 0; $s .= main->FETCH($action); print "$action: s0=$s\n";
724    $s = ''; $e = 1; eval { $s .= main->FETCH($action)}; print "$action: s1=$s\n";
725    $s = ''; $e = 0; $s .= $foo{$action}; print "$action: s2=$s\n";
726    $s = ''; $e = 1; eval { $s .= $foo{$action}}; print "$action: s3=$s\n";
727}
7281 while unlink $file;
729
730$foo{'exit'};
731print "overshot main\n"; # shouldn't reach here
732
733EXPECT
734eval: s0=EVAL-BD-BS-E1-S1-E2-S2-R
735eval: s1=EVAL-BD-BS-E1-S1-E2-S2-R
736eval: s2=EVAL-BD-BS-E1-S1-E2-S2-R
737eval: s3=EVAL-BD-BS-E1-S1-E2-S2-R
738require: s0=REQUIRE-0-ERQ-ENDRQ-1-ERQ-ENDRQ-2-ERQ-ENDRQ-3-ERQ-ENDRQ-R
739require: s1=REQUIRE-0-RQ
740require: s2=REQUIRE-0-ERQ-ENDRQ-1-ERQ-ENDRQ-2-ERQ-ENDRQ-3-ERQ-ENDRQ-R
741require: s3=REQUIRE-0-RQ
742########
743# RT 8857: STORE incorrectly invoked for local($_) on aliased tied array
744#          element
745
746sub TIEARRAY { bless [], $_[0] }
747sub TIEHASH  { bless [], $_[0] }
748sub FETCH { $_[0]->[$_[1]] }
749sub STORE { $_[0]->[$_[1]] = $_[2] }
750
751
752sub f {
753    local $_[0];
754}
755tie @a, 'main';
756tie %h, 'main';
757
758foreach ($a[0], $h{a}) {
759    f($_);
760}
761# on failure, chucks up 'premature free' etc messages
762EXPECT
763########
764# RT 5475:
765# the initial fix for this bug caused tied scalar FETCH to be called
766# multiple times when that scalar was an element in an array. Check it
767# only gets called once now.
768
769sub TIESCALAR { bless [], $_[0] }
770my $c = 0;
771sub FETCH { $c++; 0 }
772sub FETCHSIZE { 1 }
773sub STORE { $c += 100; 0 }
774
775
776my (@a, %h);
777tie $a[0],   'main';
778tie $h{foo}, 'main';
779
780my $i = 0;
781my $x = $a[0] + $h{foo} + $a[$i] + (@a)[0];
782print "x=$x c=$c\n";
783EXPECT
784x=0 c=4
785########
786# Bug 68192 - numeric ops not calling mg_get when tied scalar holds a ref
787sub TIESCALAR { bless {}, __PACKAGE__ };
788sub STORE {};
789sub FETCH {
790 print "fetching... "; # make sure FETCH is called once per op
791 123456
792};
793my $foo;
794tie $foo, __PACKAGE__;
795my $a = [1234567];
796$foo = $a;
797print "+   ", 0 + $foo, "\n";
798print "**  ", $foo**1, "\n";
799print "*   ", $foo*1, "\n";
800print "/   ", $foo*1, "\n";
801print "%   ", $foo%123457, "\n";
802print "-   ", $foo-0, "\n";
803print "neg ", - -$foo, "\n";
804print "int ", int $foo, "\n";
805print "abs ", abs $foo, "\n";
806print "==  ", 123456 == $foo, "\n";
807print "<   ", 123455 < $foo, "\n";
808print ">   ", 123457 > $foo, "\n";
809print "<=  ", 123456 <= $foo, "\n";
810print ">=  ", 123456 >= $foo, "\n";
811print "!=  ", 0 != $foo, "\n";
812print "<=> ", 123457 <=> $foo, "\n";
813EXPECT
814fetching... +   123456
815fetching... **  123456
816fetching... *   123456
817fetching... /   123456
818fetching... %   123456
819fetching... -   123456
820fetching... neg 123456
821fetching... int 123456
822fetching... abs 123456
823fetching... ==  1
824fetching... <   1
825fetching... >   1
826fetching... <=  1
827fetching... >=  1
828fetching... !=  1
829fetching... <=> 1
830########
831# Ties returning overloaded objects
832{
833 package overloaded;
834 use overload
835  '*{}' => sub { print '*{}'; \*100 },
836  '@{}' => sub { print '@{}'; \@100 },
837  '%{}' => sub { print '%{}'; \%100 },
838  '${}' => sub { print '${}'; \$100 },
839  map {
840   my $op = $_;
841   $_ => sub { print "$op"; 100 }
842  } qw< 0+ "" + ** * / % - neg int abs == < > <= >= != <=> <> >
843}
844$o = bless [], overloaded;
845
846sub TIESCALAR { bless {}, "" }
847sub FETCH { print "fetching... "; $o }
848sub STORE{}
849tie $ghew, "";
850
851$ghew=undef; 1+$ghew; print "\n";
852$ghew=undef; $ghew**1; print "\n";
853$ghew=undef; $ghew*1; print "\n";
854$ghew=undef; $ghew/1; print "\n";
855$ghew=undef; $ghew%1; print "\n";
856$ghew=undef; $ghew-1; print "\n";
857$ghew=undef; -$ghew; print "\n";
858$ghew=undef; int $ghew; print "\n";
859$ghew=undef; abs $ghew; print "\n";
860$ghew=undef; 1 == $ghew; print "\n";
861$ghew=undef; $ghew<1; print "\n";
862$ghew=undef; $ghew>1; print "\n";
863$ghew=undef; $ghew<=1; print "\n";
864$ghew=undef; $ghew >=1; print "\n";
865$ghew=undef; $ghew != 1; print "\n";
866$ghew=undef; $ghew<=>1; print "\n";
867$ghew=undef; <$ghew>; print "\n";
868$ghew=\*shrext; *$ghew; print "\n";
869$ghew=\@spled; @$ghew; print "\n";
870$ghew=\%frit; %$ghew; print "\n";
871$ghew=\$drile; $$ghew; print "\n";
872EXPECT
873fetching... +
874fetching... **
875fetching... *
876fetching... /
877fetching... %
878fetching... -
879fetching... neg
880fetching... int
881fetching... abs
882fetching... ==
883fetching... <
884fetching... >
885fetching... <=
886fetching... >=
887fetching... !=
888fetching... <=>
889fetching... <>
890fetching... *{}
891fetching... @{}
892fetching... %{}
893fetching... ${}
894########
895# RT 51636: segmentation fault with array ties
896
897tie my @a, 'T';
898@a = (1);
899print "ok\n"; # if we got here we didn't crash
900
901package T;
902
903sub TIEARRAY { bless {} }
904sub STORE    { tie my @b, 'T' }
905sub CLEAR    { }
906sub EXTEND   { }
907
908EXPECT
909ok
910########
911# RT 8438: Tied scalars don't call FETCH when subref is dereferenced
912
913sub TIESCALAR { bless {} }
914
915my $fetch = 0;
916my $called = 0;
917sub FETCH { $fetch++; sub { $called++ } }
918
919tie my $f, 'main';
920$f->(1) for 1,2;
921print "fetch=$fetch\ncalled=$called\n";
922
923EXPECT
924fetch=2
925called=2
926########
927# tie mustn't attempt to call methods on bareword filehandles.
928sub IO::File::TIEARRAY {
929    die "Did not want to invoke IO::File::TIEARRAY";
930}
931fileno FOO; tie @a, "FOO"
932EXPECT
933Can't locate object method "TIEARRAY" via package "FOO" (perhaps you forgot to load "FOO"?) at - line 5.
934########
935# tie into empty package name
936tie $foo, "";
937EXPECT
938Can't locate object method "TIESCALAR" via package "main" at - line 2.
939########
940# tie into undef package name
941tie $foo, undef;
942EXPECT
943Can't locate object method "TIESCALAR" via package "main" at - line 2.
944########
945# tie into nonexistent glob [RT#130623 assertion failure]
946tie $foo, *FOO;
947EXPECT
948Can't locate object method "TIESCALAR" via package "FOO" at - line 2.
949########
950# tie into glob when package exists but not method: no "*", no "main::"
951{ package PackageWithoutTIESCALAR }
952tie $foo, *PackageWithoutTIESCALAR;
953EXPECT
954Can't locate object method "TIESCALAR" via package "PackageWithoutTIESCALAR" at - line 3.
955########
956# tie into reference [RT#130623 assertion failure]
957eval { tie $foo, \"nope" };
958my $exn = $@ // "";
959print $exn =~ s/0x\w+/0xNNN/rg;
960EXPECT
961Can't locate object method "TIESCALAR" via package "SCALAR(0xNNN)" at - line 2.
962########
963#
964# STORE freeing tie'd AV
965sub TIEARRAY  { bless [] }
966sub STORE     { *a = []; 1 }
967sub STORESIZE { }
968sub EXTEND    { }
969tie @a, 'main';
970$a[0] = 1;
971EXPECT
972########
973#
974# CLEAR freeing tie'd AV
975sub TIEARRAY  { bless [] }
976sub CLEAR     { *a = []; 1 }
977sub STORESIZE { }
978sub EXTEND    { }
979sub STORE     { }
980tie @a, 'main';
981@a = (1,2,3);
982EXPECT
983########
984#
985# FETCHSIZE freeing tie'd AV
986sub TIEARRAY  { bless [] }
987sub FETCHSIZE { *a = []; 100 }
988sub STORESIZE { }
989sub EXTEND    { }
990sub STORE     { }
991tie @a, 'main';
992print $#a,"\n"
993EXPECT
99499
995########
996#
997# [perl #86328] Crash when freeing tie magic that can increment the refcnt
998
999no warnings 'experimental::builtin';
1000use builtin 'weaken';
1001
1002sub TIEHASH {
1003    return $_[1];
1004}
1005*TIEARRAY = *TIEHASH;
1006
1007sub DESTROY {
1008    my ($tied) = @_;
1009    my $b = $tied->[0];
1010}
1011
1012my $a = {};
1013my $o = bless [];
1014weaken($o->[0] = $a);
1015tie %$a, "main", $o;
1016
1017my $b = [];
1018my $p = bless [];
1019weaken($p->[0] = $b);
1020tie @$b, "main", $p;
1021
1022# Done setting up the evil data structures
1023
1024$a = undef;
1025$b = undef;
1026print "ok\n";
1027
1028EXPECT
1029ok
1030########
1031#
1032# Localising a tied COW scalar should not make it read-only.
1033
1034sub TIESCALAR { bless [] }
1035sub FETCH { __PACKAGE__ }
1036sub STORE {}
1037tie $x, "";
1038"$x";
1039{
1040    local $x;
1041    $x = 3;
1042}
1043print "ok\n";
1044EXPECT
1045ok
1046########
1047#
1048# Nor should it be impossible to tie COW scalars that are already PVMGs.
1049
1050sub TIESCALAR { bless [] }
1051$x = *foo;        # PVGV
1052undef $x;         # downgrade to PVMG
1053$x = __PACKAGE__; # PVMG + COW
1054tie $x, "";       # bang!
1055
1056print STDERR "ok\n";
1057
1058# However, one should not be able to tie read-only glob copies, which look
1059# a bit like kine internally (FAKE + READONLY).
1060$y = *foo;
1061Internals::SvREADONLY($y,1);
1062tie $y, "";
1063
1064EXPECT
1065ok
1066Modification of a read-only value attempted at - line 16.
1067########
1068#
1069# And one should not be able to tie read-only COWs
1070for(__PACKAGE__) { tie $_, "" }
1071sub TIESCALAR {bless []}
1072EXPECT
1073Modification of a read-only value attempted at - line 3.
1074########
1075
1076# Similarly, read-only regexps cannot be tied.
1077sub TIESCALAR { bless [] }
1078$y = ${qr//};
1079Internals::SvREADONLY($y,1);
1080tie $y, "";
1081
1082EXPECT
1083Modification of a read-only value attempted at - line 6.
1084########
1085
1086# tied() should still work on tied scalars after glob assignment
1087sub TIESCALAR {bless[]}
1088sub FETCH {*foo}
1089sub f::TIEHANDLE{bless[],f}
1090tie *foo, "f";
1091tie $rin, "";
1092[$rin]; # call FETCH
1093print ref tied $rin, "\n";
1094print ref tied *$rin, "\n";
1095EXPECT
1096main
1097f
1098########
1099
1100# (un)tie $glob_copy vs (un)tie *$glob_copy
1101sub TIESCALAR { print "TIESCALAR\n"; bless [] }
1102sub TIEHANDLE{ print "TIEHANDLE\n"; bless [] }
1103sub FETCH { print "never called\n" }
1104$f = *foo;
1105tie *$f, "";
1106tie $f, "";
1107untie $f;
1108print "ok 1\n" if !tied $f;
1109() = $f; # should not call FETCH
1110untie *$f;
1111print "ok 2\n" if !tied *foo;
1112EXPECT
1113TIEHANDLE
1114TIESCALAR
1115ok 1
1116ok 2
1117########
1118
1119# RT #8611 mustn't goto outside the magic stack
1120sub TIESCALAR { warn "tiescalar\n"; bless [] }
1121sub FETCH { warn "fetch()\n"; goto FOO; }
1122tie $f, "";
1123warn "before fetch\n";
1124my $a = "$f";
1125warn "before FOO\n";
1126FOO:
1127warn "after FOO\n";
1128EXPECT
1129tiescalar
1130before fetch
1131fetch()
1132Can't find label FOO at - line 4.
1133########
1134
1135# RT #8611 mustn't goto outside the magic stack
1136sub TIEHANDLE { warn "tiehandle\n"; bless [] }
1137sub PRINT { warn "print()\n"; goto FOO; }
1138tie *F, "";
1139warn "before print\n";
1140print F "abc";
1141warn "before FOO\n";
1142FOO:
1143warn "after FOO\n";
1144EXPECT
1145tiehandle
1146before print
1147print()
1148Can't find label FOO at - line 4.
1149########
1150
1151# \&$tied with $tied holding a reference before the fetch (but not after)
1152sub ::72 { 73 };
1153sub TIESCALAR {bless[]}
1154sub STORE{}
1155sub FETCH { 72 }
1156tie my $x, "main";
1157$x = \$y;
1158\&$x;
1159print "ok\n";
1160EXPECT
1161ok
1162########
1163
1164# \&$tied with $tied holding a PVLV glob before the fetch (but not after)
1165sub ::72 { 73 };
1166sub TIEARRAY {bless[]}
1167sub STORE{}
1168sub FETCH { 72 }
1169tie my @x, "main";
1170my $elem = \$x[0];
1171$$elem = *bar;
1172print &{\&$$elem}, "\n";
1173EXPECT
117473
1175########
1176
1177# \&$tied with $tied holding a PVGV glob before the fetch (but not after)
1178local *72 = sub { 73 };
1179sub TIESCALAR {bless[]}
1180sub STORE{}
1181sub FETCH { 72 }
1182tie my $x, "main";
1183$x = *bar;
1184print &{\&$x}, "\n";
1185EXPECT
118673
1187########
1188
1189# Lexicals should not be visible to magic methods on scope exit
1190BEGIN { unless (defined &DynaLoader::boot_DynaLoader) {
1191    print "HASH\nHASH\nARRAY\nARRAY\n"; exit;
1192}}
1193no warnings 'experimental::builtin';
1194use builtin 'weaken';
1195{ package xoufghd;
1196  sub TIEHASH { weaken($_[1]); bless \$_[1], xoufghd:: }
1197  *TIEARRAY = *TIEHASH;
1198  DESTROY {
1199     bless ${$_[0]} || return, 0;
1200} }
1201for my $sub (
1202    # hashes: ties before backrefs
1203    sub {
1204        my %hash;
1205        $ref = ref \%hash;
1206        tie %hash, xoufghd::, \%hash;
1207        1;
1208    },
1209    # hashes: backrefs before ties
1210    sub {
1211        my %hash;
1212        $ref = ref \%hash;
1213        weaken(my $x = \%hash);
1214        tie %hash, xoufghd::, \%hash;
1215        1;
1216    },
1217    # arrays: ties before backrefs
1218    sub {
1219        my @array;
1220        $ref = ref \@array;
1221        tie @array, xoufghd::, \@array;
1222        1;
1223    },
1224    # arrays: backrefs before ties
1225    sub {
1226        my @array;
1227        $ref = ref \@array;
1228        weaken(my $x = \@array);
1229        tie @array, xoufghd::, \@array;
1230        1;
1231    },
1232) {
1233    &$sub;
1234    &$sub;
1235    print $ref, "\n";
1236}
1237EXPECT
1238HASH
1239HASH
1240ARRAY
1241ARRAY
1242########
1243
1244# Localising a tied variable with a typeglob in it should copy magic
1245sub TIESCALAR{bless[]}
1246sub FETCH{warn "fetching\n"; *foo}
1247sub STORE{}
1248tie $x, "";
1249local $x;
1250warn "before";
1251"$x";
1252warn "after";
1253EXPECT
1254fetching
1255before at - line 8.
1256fetching
1257after at - line 10.
1258########
1259
1260# tied returns same value as tie
1261sub TIESCALAR{bless[]}
1262$tyre = \tie $tied, "";
1263print "ok\n" if \tied $tied == $tyre;
1264EXPECT
1265ok
1266########
1267
1268# tied arrays should always be AvREAL
1269$^W=1;
1270sub TIEARRAY{bless[]}
1271sub {
1272  tie @_, "";
1273  \@_; # used to produce: av_reify called on tied array at - line 7.
1274}->(1);
1275EXPECT
1276########
1277
1278# [perl #67490] scalar-tying elements of magic hashes
1279sub TIESCALAR{bless[]}
1280sub STORE{}
1281tie $ENV{foo}, '';
1282$ENV{foo} = 78;
1283delete $ENV{foo};
1284tie $^H{foo}, '';
1285$^H{foo} = 78;
1286delete $^H{foo};
1287EXPECT
1288########
1289
1290# [perl #35865, #43011] autovivification should call FETCH after STORE
1291# because perl does not know that the FETCH would have returned the same
1292# thing that was just stored.
1293
1294# This package never likes to take ownership of other people’s refs.  It
1295# always makes its own copies.  (For simplicity, it only accepts hashes.)
1296package copier {
1297    sub TIEHASH { bless {} }
1298    sub FETCH   { $_[0]{$_[1]} }
1299    sub STORE   { $_[0]{$_[1]} = { %{ $_[2] } } }
1300}
1301tie my %h, copier::;
1302$h{i}{j} = 'k';
1303print $h{i}{j}, "\n";
1304EXPECT
1305k
1306########
1307
1308# [perl #8931] FETCH for tied $" called an odd number of times.
1309use strict;
1310my $i = 0;
1311sub A::TIESCALAR {bless [] => 'A'}
1312sub A::FETCH {print ++ $i, "\n"}
1313my @a = ("", "", "");
1314
1315tie $" => 'A';
1316"@a";
1317
1318$i = 0;
1319tie my $a => 'A';
1320join $a, 1..10;
1321EXPECT
13221
13231
1324########
1325
1326# [perl #9391] return value from 'tied' not discarded soon enough
1327use warnings;
1328tie @a, 'T';
1329if (tied @a) {
1330untie @a;
1331}
1332
1333sub T::TIEARRAY { my $s; bless \$s => "T" }
1334EXPECT
1335########
1336
1337# NAME Test that tying a hash does not leak a deleted iterator
1338# This produced unbalanced string table warnings under
1339# PERL_DESTRUCT_LEVEL=2.
1340package l {
1341    sub TIEHASH{bless[]}
1342}
1343$h = {foo=>0};
1344each %$h;
1345delete $$h{foo};
1346tie %$h, 'l';
1347EXPECT
1348########
1349
1350# NAME EXISTS on arrays
1351sub TIEARRAY{bless[]};
1352sub FETCHSIZE { 50 }
1353sub EXISTS { print "does $_[1] exist?\n" }
1354tie @a, "";
1355exists $a[1];
1356exists $a[-1];
1357$NEGATIVE_INDICES=1;
1358exists $a[-1];
1359EXPECT
1360does 1 exist?
1361does 49 exist?
1362does -1 exist?
1363########
1364
1365# Crash when using negative index on array tied to non-object
1366sub TIEARRAY{bless[]};
1367${\tie @a, ""} = undef;
1368eval { $_ = $a[-1] }; print $@;
1369eval { $a[-1] = '' }; print $@;
1370eval { delete $a[-1] }; print $@;
1371eval { exists $a[-1] }; print $@;
1372
1373EXPECT
1374Can't call method "FETCHSIZE" on an undefined value at - line 5.
1375Can't call method "FETCHSIZE" on an undefined value at - line 6.
1376Can't call method "FETCHSIZE" on an undefined value at - line 7.
1377Can't call method "FETCHSIZE" on an undefined value at - line 8.
1378########
1379
1380# Crash when reading negative index when NEGATIVE_INDICES stub exists
1381sub NEGATIVE_INDICES;
1382sub TIEARRAY{bless[]};
1383sub FETCHSIZE{}
1384tie @a, "";
1385print "ok\n" if ! defined $a[-1];
1386EXPECT
1387ok
1388########
1389
1390# Assigning vstrings to tied scalars
1391sub TIESCALAR{bless[]};
1392sub STORE { print ref \$_[1], "\n" }
1393tie $x, ""; $x = v3;
1394EXPECT
1395VSTRING
1396########
1397
1398# [perl #27010] Tying deferred elements
1399$\="\n";
1400sub TIESCALAR{bless[]};
1401sub {
1402    tie $_[0], "";
1403    print ref tied $h{k};
1404    tie $h{l}, "";
1405    print ref tied $_[1];
1406    untie $h{k};
1407    print tied $_[0] // 'undef';
1408    untie $_[1];
1409    print tied $h{l} // 'undef';
1410    # check that tied and untie do not autovivify
1411    # XXX should they autovivify?
1412    tied $_[2];
1413    print exists $h{m} ? "yes" : "no";
1414    untie $_[2];
1415    print exists $h{m} ? "yes" : "no";
1416}->($h{k}, $h{l}, $h{m});
1417EXPECT
1418main
1419main
1420undef
1421undef
1422no
1423no
1424########
1425
1426# [perl #78194] Passing op return values to tie constructors
1427sub TIEARRAY{
1428    print \$_[1] == \$_[1] ? "ok\n" : "not ok\n";
1429};
1430tie @a, "", "$a$b";
1431EXPECT
1432ok
1433########
1434
1435# Scalar-tied locked hash keys and copy-on-write
1436use Tie::Scalar;
1437tie $h{foo}, Tie::StdScalar;
1438tie $h{bar}, Tie::StdScalar;
1439$h{foo} = __PACKAGE__; # COW
1440$h{bar} = 1;       # not COW
1441# Moral equivalent of Hash::Util::lock_whatever, but miniperl-compatible
1442Internals::SvREADONLY($h{foo},1);
1443Internals::SvREADONLY($h{bar},1);
1444print $h{foo}, "\n"; # should not croak
1445# Whether the value is COW should make no difference here (whether the
1446# behaviour is ultimately correct is another matter):
1447local $h{foo};
1448local $h{bar};
1449print "ok\n" if (eval{ $h{foo} = 1 }||$@) eq (eval{ $h{bar} = 1 }||$@);
1450EXPECT
1451main
1452ok
1453########
1454# SKIP ? $::IS_EBCDIC
1455# skipped on EBCDIC because different from ASCII and results vary depending on
1456# code page
1457
1458# &xsub and goto &xsub with tied @_
1459use Tie::Array;
1460tie @_, Tie::StdArray;
1461@_ = "\xff";
1462&utf8::encode;
1463printf "%x\n", $_ for map ord, split //, $_[0];
1464print "--\n";
1465@_ = "\xff";
1466& {sub { goto &utf8::encode }};
1467printf "%x\n", $_ for map ord, split //, $_[0];
1468EXPECT
1469c3
1470bf
1471--
1472c3
1473bf
1474########
1475
1476# Defelem pointing to nonexistent element of tied array
1477
1478use Tie::Array;
1479# This sub is called with a deferred element.  Inside the sub, $_[0] pros-
1480# pectively points to element 10000 of @a.
1481sub {
1482  tie @a, "Tie::StdArray";  # now @a is tied
1483  $#a = 20000;  # and FETCHSIZE/AvFILL will now return a big number
1484  $a[10000] = "crumpets\n";
1485  $_ = "$_[0]"; # but defelems don't expect tied arrays and try to read
1486                # AvARRAY[10000], which crashes
1487}->($a[10000]);
1488print
1489EXPECT
1490crumpets
1491########
1492
1493# tied() in list assignment
1494
1495sub TIESCALAR : lvalue {
1496    ${+pop} = bless [], shift;
1497}
1498tie $t, "", \$a;
1499$a = 7;
1500($a, $b) = (3, tied $t);
1501print "a is $a\n";
1502print "b is $b\n";
1503EXPECT
1504a is 3
1505b is 7
1506########
1507# when assigning to array/hash, ensure get magic is processed first
1508use Tie::Hash;
1509my %tied;
1510tie %tied, "Tie::StdHash";
1511%tied = qw(a foo);
1512my @a = values %tied;
1513%tied = qw(b bar); # overwrites @a's contents unless magic was called
1514print "$a[0]\n";
1515my %h = ("x", values %tied);
1516%tied = qw(c baz); # overwrites @a's contents unless magic was called
1517print "$h{x}\n";
1518
1519EXPECT
1520foo
1521bar
1522########
1523# keys(%tied) in bool context without SCALAR present
1524my ($f,$n) = (0,0);
1525my %inner = (a =>1, b => 2, c => 3);
1526sub TIEHASH  { bless \%inner, $_[0] }
1527sub FIRSTKEY { $f++; my $a = scalar keys %{$_[0]}; each %{$_[0]} }
1528sub NEXTKEY  { $n++; each %{$_[0]} }
1529tie %h, 'main';
1530my $x = !keys %h;
1531print "[$x][$f][$n]\n";
1532%inner = ();
1533$x = !keys %h;
1534print "[$x][$f][$n]\n";
1535EXPECT
1536[][1][0]
1537[1][2][0]
1538########
1539# keys(%tied) in bool context with SCALAR present
1540my ($f,$n, $s) = (0,0,0);
1541my %inner = (a =>1, b => 2, c => 3);
1542sub TIEHASH  { bless \%inner, $_[0] }
1543sub FIRSTKEY { $f++; my $a = scalar keys %{$_[0]}; each %{$_[0]} }
1544sub NEXTKEY  { $n++; each %{$_[0]} }
1545sub SCALAR   { $s++; scalar %{$_[0]} }
1546tie %h, 'main';
1547my $x = !keys %h;
1548print "[$x][$f][$n][$s]\n";
1549%inner = ();
1550$x = !keys %h;
1551print "[$x][$f][$n][$s]\n";
1552EXPECT
1553[][0][0][1]
1554[1][0][0][2]
1555########
1556# keys(%tied) in scalar context without SCALAR present
1557my ($f,$n) = (0,0);
1558my %inner = (a =>1, b => 2, c => 3);
1559sub TIEHASH  { bless \%inner, $_[0] }
1560sub FIRSTKEY { $f++; my $a = scalar keys %{$_[0]}; each %{$_[0]} }
1561sub NEXTKEY  { $n++; each %{$_[0]} }
1562tie %h, 'main';
1563my $x = keys %h;
1564print "[$x][$f][$n]\n";
1565%inner = ();
1566$x = keys %h;
1567print "[$x][$f][$n]\n";
1568EXPECT
1569[3][1][3]
1570[0][2][3]
1571########
1572# keys(%tied) in scalar context with SCALAR present
1573# XXX the behaviour of scalar(keys(%tied)) may change - it currently
1574# doesn't make use of SCALAR() if present
1575my ($f,$n, $s) = (0,0,0);
1576my %inner = (a =>1, b => 2, c => 3);
1577sub TIEHASH  { bless \%inner, $_[0] }
1578sub FIRSTKEY { $f++; my $a = scalar keys %{$_[0]}; each %{$_[0]} }
1579sub NEXTKEY  { $n++; each %{$_[0]} }
1580sub SCALAR   { $s++; scalar %{$_[0]} }
1581tie %h, 'main';
1582my $x = keys %h;
1583print "[$x][$f][$n][$s]\n";
1584%inner = ();
1585$x = keys %h;
1586print "[$x][$f][$n][$s]\n";
1587EXPECT
1588[3][1][3][0]
1589[0][2][3][0]
1590########
1591# dying while doing a SAVEt_DELETE dureing scope exit leaked a copy of the
1592# key. Give ASan something to play with
1593sub TIEHASH { bless({}, $_[0]) }
1594sub EXISTS { 0 }
1595sub DELETE { die; }
1596sub DESTROY { print "destroy\n"; }
1597
1598eval {
1599    my %h;
1600    tie %h, "main";
1601    local $h{foo};
1602    print "leaving\n";
1603};
1604print "left\n";
1605EXPECT
1606leaving
1607destroy
1608left
1609########
1610# ditto for SAVEt_DELETE with an array
1611sub TIEARRAY { bless({}, $_[0]) }
1612sub EXISTS { 0 }
1613sub DELETE { die; }
1614sub DESTROY { print "destroy\n"; }
1615
1616eval {
1617    my @a;
1618    tie @a, "main";
1619    delete local $a[0];
1620    print "leaving\n";
1621};
1622print "left\n";
1623EXPECT
1624leaving
1625destroy
1626left
1627########
1628# This is not intended as a test of *correctness*. The precise ordering of all
1629# the events here is observable by code on CPAN, so potentially some of it will
1630# inadvertently be relying on it (and likely not in any regression test)
1631# Hence this "test" here is intended as a way to alert us if any core code
1632# change has the side effect of alerting this observable behaviour, so that we
1633# can document it in the perldelta.
1634package Note {
1635    sub new {
1636        my ($class, $note) = @_;
1637        bless \$note, $class;
1638    }
1639
1640    sub DESTROY {
1641        my $self = shift;
1642        print "Destroying $$self\n";
1643    }
1644};
1645
1646package Infinity {
1647    sub TIEHASH {
1648        my $zero = 0;
1649        bless \$zero, shift;
1650    }
1651
1652    sub FIRSTKEY {
1653        my $self = shift;
1654        Note->new($$self);
1655    }
1656
1657    sub NEXTKEY {
1658        my $self = shift;
1659        Note->new(++$$self);
1660    }
1661};
1662
1663# Iteration on tied hashes is implemented by storing a copy of the last reported
1664# key within the hash, passing it to NEXTKEY, and then freeing it (in order to
1665# store the SV for the newly returned key)
1666
1667# Here FIRSTKEY/NEXTKEY return keys that are references to objects...
1668
1669my %h;
1670tie %h, 'Infinity';
1671
1672my $k;
1673print "Start\n";
1674$k = each %h;
1675printf "FIRSTKEY is %s %s\n", ref $k, $$k;
1676
1677# each calls iternext_flags, hence this is where the previous key is freed
1678
1679$k = each %h;
1680printf "NEXTKEY is %s %s\n", ref $k, $$k;
1681undef $k;
1682# Our reference to the object is gone, but a reference remains within %h, so
1683# DESTROY isn't triggered.
1684
1685print "Before untie\n";
1686untie %h;
1687print "After untie\n";
1688
1689# Currently if tied hash iteration is incomplete at the untie, the SV recording
1690# the last returned key is only freed if regular hash iteration is attempted.
1691
1692print "Before regular iteration\n";
1693$k = each %h;
1694print "After regular iteration\n";
1695
1696EXPECT
1697Start
1698FIRSTKEY is Note 0
1699Destroying 0
1700NEXTKEY is Note 1
1701Before untie
1702Destroying 1
1703After untie
1704Before regular iteration
1705After regular iteration
1706