This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Get tie.t working under minitest
[perl5.git] / t / op / tie.t
CommitLineData
49d42823
PP
1#!./perl
2
d87ebaca
YST
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#
49d42823
PP
11
12chdir 't' if -d 't';
20822f61 13@INC = '../lib';
5f7e0818 14require './test.pl';
49d42823
PP
15
16$|=1;
17
5f7e0818 18run_multiple_progs('', \*DATA);
d87ebaca 19
5f7e0818 20done_testing();
49d42823
PP
21
22__END__
23
24# standard behaviour, without any extra references
25use Tie::Hash ;
26tie %h, Tie::StdHash;
27untie %h;
28EXPECT
29########
19295df3
FC
30# SKIP !defined &DynaLoader::boot_DynaLoader && !eval 'require base'
31# (skip under miniperl if base.pm is not in lib/ yet)
49d42823 32
a29a5827
NIS
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
49d42823
PP
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
4438c4b7 81use warnings 'untie';
49d42823
PP
82use Tie::Hash ;
83tie %h, Tie::StdHash;
84untie %h;
85EXPECT
86########
87
88# strict behaviour, with 1 extra references generating an error
4438c4b7 89use warnings 'untie';
49d42823
PP
90use Tie::Hash ;
91$a = tie %h, Tie::StdHash;
92untie %h;
93EXPECT
d87ebaca 94untie attempted while 1 inner references still exist at - line 6.
49d42823
PP
95########
96
97# strict behaviour, with 1 extra references via tied generating an error
4438c4b7 98use warnings 'untie';
49d42823
PP
99use Tie::Hash ;
100tie %h, Tie::StdHash;
101$a = tied %h;
102untie %h;
103EXPECT
d87ebaca 104untie attempted while 1 inner references still exist at - line 7.
49d42823
PP
105########
106
107# strict behaviour, with 1 extra references which are destroyed
4438c4b7 108use warnings 'untie';
49d42823
PP
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
4438c4b7 117use warnings 'untie';
49d42823
PP
118use Tie::Hash ;
119tie %h, Tie::StdHash;
120$a = tied %h;
121$a = 0 ;
122untie %h;
123EXPECT
124########
125
87f0b213 126# strict error behaviour, with 2 extra references
4438c4b7 127use warnings 'untie';
49d42823
PP
128use Tie::Hash ;
129$a = tie %h, Tie::StdHash;
130$b = tied %h ;
131untie %h;
132EXPECT
d87ebaca 133untie attempted while 2 inner references still exist at - line 7.
49d42823
PP
134########
135
136# strict behaviour, check scope of strictness.
4438c4b7 137no warnings 'untie';
49d42823
PP
138use Tie::Hash ;
139$A = tie %H, Tie::StdHash;
140$C = $B = tied %H ;
141{
4438c4b7 142 use warnings 'untie';
49d42823
PP
143 use Tie::Hash ;
144 tie %h, Tie::StdHash;
145 untie %h;
146}
147untie %H;
148EXPECT
33c27489 149########
d87ebaca 150
ae21d580 151# Forbidden aggregate self-ties
33c27489 152sub Self::TIEHASH { bless $_[1], $_[0] }
ae21d580 153{
d87ebaca 154 my %c;
ae21d580
JH
155 tie %c, 'Self', \%c;
156}
157EXPECT
d87ebaca 158Self-ties of arrays and hashes are not supported at - line 6.
ae21d580 159########
d87ebaca 160
ae21d580 161# Allowed scalar self-ties
d87ebaca 162my $destroyed = 0;
ae21d580 163sub Self::TIESCALAR { bless $_[1], $_[0] }
d87ebaca 164sub Self::DESTROY { $destroyed = 1; }
33c27489 165{
ae21d580 166 my $c = 42;
ae21d580 167 tie $c, 'Self', \$c;
33c27489 168}
d87ebaca 169die "self-tied scalar not DESTROYed" unless $destroyed == 1;
7bb043c3 170EXPECT
83f527ec 171########
3ca7705e 172
b5ccf5f2 173# Allowed glob self-ties
87f0b213
JH
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;
43bb546a 186die "self-tied glob not DESTROYed" unless $destroyed == 1;
87f0b213
JH
187EXPECT
188########
189
190# Allowed IO self-ties
191my $destroyed = 0;
192sub Self3::TIEHANDLE { bless $_[1], $_[0] }
193sub Self3::DESTROY { $destroyed = 1; }
b5ccf5f2 194sub Self3::PRINT { $printed = 1; }
87f0b213
JH
195{
196 use Symbol 'geniosym';
197 my $c = geniosym;
198 tie *$c, 'Self3', $c;
b5ccf5f2 199 print $c 'Hello';
87f0b213 200}
b5ccf5f2 201die "self-tied IO not PRINTed" unless $printed == 1;
43bb546a 202die "self-tied IO not DESTROYed" unless $destroyed == 1;
87f0b213
JH
203EXPECT
204########
0b2c215a 205
b5ccf5f2
YST
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
d87ebaca
YST
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.
eb85dfd3
DM
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
b77f7d40
YST
276########
277#
4bac9ae4 278# FETCH freeing tie'd SV still works
b77f7d40 279sub TIESCALAR { bless [] }
4bac9ae4 280sub FETCH { *a = \1; 2 }
b77f7d40
YST
281tie $a, 'main';
282print $a;
283EXPECT
4bac9ae4 2842
dd28f7bb
DM
285########
286
287# [20020716.007] - 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
38193a09
AM
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";
39cf747a 328my $s = $a->{foo}; # access once
38193a09
AM
329# the hash element should not be tied anymore
330print defined tied $a->{foo} ? "not ok" : "ok";
331EXPECT
332ok
be65207d
DM
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
b7056d9c
JH
350########
351# [perl #23287] segfault in untie
352sub TIESCALAR { bless $_[1], $_[0] }
353my $var;
354tie $var, 'main', \$var;
355untie $var;
356EXPECT
16e0ce55
JH
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
93f09d7b 361# above. Its odd but convenient that after untie'ing you are left with
16e0ce55
JH
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
dd12389b
JH
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
6c0731c3
RC
436########
437
e23d9e2f 438# [perl #948] cannot meaningfully tie $,
6c0731c3
RC
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;
e23d9e2f 454 print "<FETCH>";
6c0731c3
RC
455 return $$self;
456}
457package main;
458
459tie $,, 'TieDollarComma';
460$, = 'BOBBINS';
461print "join", "things", "up\n";
462EXPECT
463STORE set 'BOBBINS'
e23d9e2f 464join<FETCH>BOBBINSthings<FETCH>BOBBINSup
a3bcc51e
TP
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";
867fa1e2
YO
497print scalar %h, "\n"
498 if %h; # this should also call SCALAR but implicitly
a3bcc51e 499%h = ();
867fa1e2
YO
500print scalar %h, "\n"
501 if !%h; # this should also call SCALAR but implicitly
a3bcc51e
TP
502EXPECT
503SCALAR
867fa1e2 504SCALAR
a3bcc51e
TP
5052/2
506SCALAR
867fa1e2 507SCALAR
a3bcc51e
TP
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
2b77b520
YST
564########
565sub TIESCALAR { bless {} }
566sub FETCH { my $x = 3.3; 1 if 0+$x; $x }
567tie $h, "main";
568print $h,"\n";
569EXPECT
5703.3
c75ab21a
RH
571########
572sub TIESCALAR { bless {} }
573sub FETCH { shift()->{i} ++ }
574tie $h, "main";
575print $h.$h;
576EXPECT
57701
64207fde 578########
7de9d14e 579# Bug 53482 (and maybe others)
64207fde
RB
580sub TIESCALAR { my $foo = $_[1]; bless \$foo, $_[0] }
581sub FETCH { ${$_[0]} }
7de9d14e
B
582tie my $x1, "main", 2;
583tie my $y1, "main", 8;
584print $x1 | $y1;
585print $x1 | $y1;
586tie my $x2, "main", "2";
587tie my $y2, "main", "8";
588print $x2 | $y2;
589print $x2 | $y2;
590EXPECT
5911010::
1baaf5d7
NC
592########
593# Bug 36267
594sub TIEHASH { bless {}, $_[0] }
595sub STORE { $_[0]->{$_[1]} = $_[2] }
596sub FIRSTKEY { my $a = scalar keys %{$_[0]}; each %{$_[0]} }
597sub NEXTKEY { each %{$_[0]} }
598sub DELETE { delete $_[0]->{$_[1]} }
599sub CLEAR { %{$_[0]} = () }
600$h{b}=1;
601delete $h{b};
602print scalar keys %h, "\n";
603tie %h, 'main';
604$i{a}=1;
605%h = %i;
606untie %h;
607print scalar keys %h, "\n";
608EXPECT
6090
6100
ced497e2
YST
611########
612# Bug 37731
613sub foo::TIESCALAR { bless {value => $_[1]}, $_[0] }
614sub foo::FETCH { $_[0]->{value} }
615tie my $VAR, 'foo', '42';
616foreach my $var ($VAR) {
617 print +($var eq $VAR) ? "yes\n" : "no\n";
618}
619EXPECT
620yes
f4c21a45
DM
621########
622sub TIEARRAY { bless [], 'main' }
623{
624 local @a;
625 tie @a, 'main';
626}
627print "tied\n" if tied @a;
628EXPECT
629########
630sub TIEHASH { bless [], 'main' }
631{
632 local %h;
633 tie %h, 'main';
634}
635print "tied\n" if tied %h;
636EXPECT
099be4f1
DM
637########
638# RT 20727: PL_defoutgv is left as a tied element
639sub TIESCALAR { return bless {}, 'main' }
640
641sub STORE {
642 select($_[1]);
643 $_[1] = 1;
644 select(); # this used to coredump or assert fail
645}
646tie $SELECT, 'main';
647$SELECT = *STDERR;
648EXPECT
27e90453
DM
649########
650# RT 23810: eval in die in FETCH can corrupt context stack
651
652my $file = 'rt23810.pm';
653
654my $e;
655my $s;
656
657sub do_require {
658 my ($str, $eval) = @_;
659 open my $fh, '>', $file or die "Can't create $file: $!\n";
660 print $fh $str;
661 close $fh;
662 if ($eval) {
663 $s .= '-ERQ';
664 eval { require $pm; $s .= '-ENDE' }
665 }
666 else {
667 $s .= '-RQ';
668 require $pm;
669 }
670 $s .= '-ENDRQ';
671 unlink $file;
672}
673
674sub TIEHASH { bless {} }
675
676sub FETCH {
677 # 10 or more syntax errors makes yyparse croak()
678 my $bad = q{$x+;$x+;$x+;$x+;$x+;$x+;$x+;$x+;$x+$x+;$x+;$x+;$x+;$x+;;$x+;};
679
680 if ($_[1] eq 'eval') {
681 $s .= 'EVAL';
682 eval q[BEGIN { die; $s .= '-X1' }];
683 $s .= '-BD';
684 eval q[BEGIN { $x+ }];
685 $s .= '-BS';
686 eval '$x+';
687 $s .= '-E1';
688 $s .= '-S1' while $@ =~ /syntax error at/g;
689 eval $bad;
690 $s .= '-E2';
691 $s .= '-S2' while $@ =~ /syntax error at/g;
692 }
693 elsif ($_[1] eq 'require') {
694 $s .= 'REQUIRE';
695 my @text = (
696 q[BEGIN { die; $s .= '-X1' }],
697 q[BEGIN { $x+ }],
698 '$x+',
699 $bad
700 );
701 for my $i (0..$#text) {
702 $s .= "-$i";
703 do_require($txt[$i], 0) if $e;;
704 do_require($txt[$i], 1);
705 }
706 }
707 elsif ($_[1] eq 'exit') {
708 eval q[exit(0); print "overshot eval\n"];
709 }
710 else {
711 print "unknown key: '$_[1]'\n";
712 }
713 return "-R";
714}
715my %foo;
716tie %foo, "main";
717
718for my $action(qw(eval require)) {
719 $s = ''; $e = 0; $s .= main->FETCH($action); print "$action: s0=$s\n";
720 $s = ''; $e = 1; eval { $s .= main->FETCH($action)}; print "$action: s1=$s\n";
721 $s = ''; $e = 0; $s .= $foo{$action}; print "$action: s2=$s\n";
722 $s = ''; $e = 1; eval { $s .= $foo{$action}}; print "$action: s3=$s\n";
723}
7241 while unlink $file;
725
726$foo{'exit'};
727print "overshot main\n"; # shouldn't reach here
728
729EXPECT
730eval: s0=EVAL-BD-BS-E1-S1-E2-S2-S2-S2-S2-S2-S2-S2-S2-S2-S2-R
731eval: s1=EVAL-BD-BS-E1-S1-E2-S2-S2-S2-S2-S2-S2-S2-S2-S2-S2-R
732eval: s2=EVAL-BD-BS-E1-S1-E2-S2-S2-S2-S2-S2-S2-S2-S2-S2-S2-R
733eval: s3=EVAL-BD-BS-E1-S1-E2-S2-S2-S2-S2-S2-S2-S2-S2-S2-S2-R
734require: s0=REQUIRE-0-ERQ-ENDRQ-1-ERQ-ENDRQ-2-ERQ-ENDRQ-3-ERQ-ENDRQ-R
735require: s1=REQUIRE-0-RQ
736require: s2=REQUIRE-0-ERQ-ENDRQ-1-ERQ-ENDRQ-2-ERQ-ENDRQ-3-ERQ-ENDRQ-R
737require: s3=REQUIRE-0-RQ
459defa1
DM
738########
739# RT 8857: STORE incorrectly invoked for local($_) on aliased tied array
740# element
741
742sub TIEARRAY { bless [], $_[0] }
743sub TIEHASH { bless [], $_[0] }
744sub FETCH { $_[0]->[$_[1]] }
745sub STORE { $_[0]->[$_[1]] = $_[2] }
746
747
748sub f {
749 local $_[0];
750}
751tie @a, 'main';
752tie %h, 'main';
27e90453 753
459defa1
DM
754foreach ($a[0], $h{a}) {
755 f($_);
756}
757# on failure, chucks up 'premature free' etc messages
758EXPECT
39cf747a
DM
759########
760# RT 5475:
761# the initial fix for this bug caused tied scalar FETCH to be called
762# multiple times when that scalar was an element in an array. Check it
763# only gets called once now.
764
765sub TIESCALAR { bless [], $_[0] }
766my $c = 0;
767sub FETCH { $c++; 0 }
768sub FETCHSIZE { 1 }
769sub STORE { $c += 100; 0 }
770
771
772my (@a, %h);
773tie $a[0], 'main';
774tie $h{foo}, 'main';
775
776my $i = 0;
777my $x = $a[0] + $h{foo} + $a[$i] + (@a)[0];
778print "x=$x c=$c\n";
779EXPECT
780x=0 c=4
6a5f8cbd
FC
781########
782# Bug 68192 - numeric ops not calling mg_get when tied scalar holds a ref
783sub TIESCALAR { bless {}, __PACKAGE__ };
784sub STORE {};
785sub FETCH {
786 print "fetching... "; # make sure FETCH is called once per op
787 123456
788};
789my $foo;
790tie $foo, __PACKAGE__;
791my $a = [1234567];
792$foo = $a;
793print "+ ", 0 + $foo, "\n";
794print "** ", $foo**1, "\n";
795print "* ", $foo*1, "\n";
796print "/ ", $foo*1, "\n";
797print "% ", $foo%123457, "\n";
798print "- ", $foo-0, "\n";
799print "neg ", - -$foo, "\n";
800print "int ", int $foo, "\n";
801print "abs ", abs $foo, "\n";
802print "== ", 123456 == $foo, "\n";
803print "< ", 123455 < $foo, "\n";
804print "> ", 123457 > $foo, "\n";
805print "<= ", 123456 <= $foo, "\n";
806print ">= ", 123456 >= $foo, "\n";
807print "!= ", 0 != $foo, "\n";
808print "<=> ", 123457 <=> $foo, "\n";
809EXPECT
810fetching... + 123456
811fetching... ** 123456
812fetching... * 123456
813fetching... / 123456
814fetching... % 123456
815fetching... - 123456
816fetching... neg 123456
817fetching... int 123456
818fetching... abs 123456
819fetching... == 1
820fetching... < 1
821fetching... > 1
822fetching... <= 1
823fetching... >= 1
824fetching... != 1
825fetching... <=> 1
826########
827# Ties returning overloaded objects
828{
829 package overloaded;
830 use overload
bb1bc619
FCR
831 '*{}' => sub { print '*{}'; \*100 },
832 '@{}' => sub { print '@{}'; \@100 },
833 '%{}' => sub { print '%{}'; \%100 },
834 '${}' => sub { print '${}'; \$100 },
6a5f8cbd
FC
835 map {
836 my $op = $_;
837 $_ => sub { print "$op"; 100 }
9e27fd70 838 } qw< 0+ "" + ** * / % - neg int abs == < > <= >= != <=> <> >
6a5f8cbd
FC
839}
840$o = bless [], overloaded;
841
842sub TIESCALAR { bless {}, "" }
843sub FETCH { print "fetching... "; $o }
844sub STORE{}
845tie $ghew, "";
846
847$ghew=undef; 1+$ghew; print "\n";
848$ghew=undef; $ghew**1; print "\n";
849$ghew=undef; $ghew*1; print "\n";
850$ghew=undef; $ghew/1; print "\n";
851$ghew=undef; $ghew%1; print "\n";
852$ghew=undef; $ghew-1; print "\n";
853$ghew=undef; -$ghew; print "\n";
854$ghew=undef; int $ghew; print "\n";
855$ghew=undef; abs $ghew; print "\n";
856$ghew=undef; 1 == $ghew; print "\n";
857$ghew=undef; $ghew<1; print "\n";
858$ghew=undef; $ghew>1; print "\n";
859$ghew=undef; $ghew<=1; print "\n";
860$ghew=undef; $ghew >=1; print "\n";
861$ghew=undef; $ghew != 1; print "\n";
862$ghew=undef; $ghew<=>1; print "\n";
9e27fd70 863$ghew=undef; <$ghew>; print "\n";
bb1bc619
FCR
864$ghew=\*shrext; *$ghew; print "\n";
865$ghew=\@spled; @$ghew; print "\n";
866$ghew=\%frit; %$ghew; print "\n";
867$ghew=\$drile; $$ghew; print "\n";
6a5f8cbd
FC
868EXPECT
869fetching... +
870fetching... **
871fetching... *
872fetching... /
873fetching... %
874fetching... -
875fetching... neg
876fetching... int
877fetching... abs
878fetching... ==
879fetching... <
880fetching... >
881fetching... <=
882fetching... >=
883fetching... !=
884fetching... <=>
9e27fd70 885fetching... <>
bb1bc619
FCR
886fetching... *{}
887fetching... @{}
888fetching... %{}
889fetching... ${}
3a19377b
DM
890########
891# RT 51636: segmentation fault with array ties
892
893tie my @a, 'T';
894@a = (1);
895print "ok\n"; # if we got here we didn't crash
896
897package T;
898
899sub TIEARRAY { bless {} }
900sub STORE { tie my @b, 'T' }
901sub CLEAR { }
902sub EXTEND { }
903
904EXPECT
905ok
7c75014e
DM
906########
907# RT 8438: Tied scalars don't call FETCH when subref is dereferenced
908
909sub TIESCALAR { bless {} }
910
911my $fetch = 0;
912my $called = 0;
913sub FETCH { $fetch++; sub { $called++ } }
914
915tie my $f, 'main';
916$f->(1) for 1,2;
917print "fetch=$fetch\ncalled=$called\n";
918
919EXPECT
920fetch=2
921called=2
086d2913
NC
922########
923# tie mustn't attempt to call methods on bareword filehandles.
924sub IO::File::TIEARRAY {
925 die "Did not want to invoke IO::File::TIEARRAY";
926}
927fileno FOO; tie @a, "FOO"
928EXPECT
929Can't locate object method "TIEARRAY" via package "FOO" at - line 5.
7c7df812 930########
8985fe98
DM
931#
932# STORE freeing tie'd AV
933sub TIEARRAY { bless [] }
934sub STORE { *a = []; 1 }
935sub STORESIZE { }
936sub EXTEND { }
937tie @a, 'main';
938$a[0] = 1;
939EXPECT
940########
941#
942# CLEAR freeing tie'd AV
943sub TIEARRAY { bless [] }
944sub CLEAR { *a = []; 1 }
945sub STORESIZE { }
946sub EXTEND { }
947sub STORE { }
948tie @a, 'main';
949@a = (1,2,3);
950EXPECT
951########
952#
953# FETCHSIZE freeing tie'd AV
954sub TIEARRAY { bless [] }
955sub FETCHSIZE { *a = []; 100 }
956sub STORESIZE { }
957sub EXTEND { }
958sub STORE { }
959tie @a, 'main';
960print $#a,"\n"
961EXPECT
96299
007f907e
FC
963########
964#
965# [perl #86328] Crash when freeing tie magic that can increment the refcnt
966
967eval { require Scalar::Util } or print("ok\n"), exit;
968
969sub TIEHASH {
970 return $_[1];
971}
972*TIEARRAY = *TIEHASH;
973
974sub DESTROY {
975 my ($tied) = @_;
976 my $b = $tied->[0];
977}
978
979my $a = {};
980my $o = bless [];
981Scalar::Util::weaken($o->[0] = $a);
982tie %$a, "main", $o;
983
984my $b = [];
985my $p = bless [];
986Scalar::Util::weaken($p->[0] = $b);
987tie @$b, "main", $p;
988
989# Done setting up the evil data structures
990
991$a = undef;
992$b = undef;
993print "ok\n";
994
995EXPECT
996ok
b2b95e4c
FC
997########
998#
999# Localising a tied COW scalar should not make it read-only.
1000
1001sub TIESCALAR { bless [] }
1002sub FETCH { __PACKAGE__ }
1003sub STORE {}
1004tie $x, "";
1005"$x";
1006{
1007 local $x;
1008 $x = 3;
1009}
1010print "ok\n";
1011EXPECT
1012ok
4be76e1f 1013########
e7d0a3fb
FC
1014#
1015# Nor should it be impossible to tie COW scalars that are already PVMGs.
1016
1017sub TIESCALAR { bless [] }
1018$x = *foo; # PVGV
1019undef $x; # downgrade to PVMG
1020$x = __PACKAGE__; # PVMG + COW
1021tie $x, ""; # bang!
1022
1023print STDERR "ok\n";
1024
1025# However, one should not be able to tie read-only glob copies, which look
1026# a bit like kine internally (FAKE + READONLY).
1027$y = *foo;
1028Internals::SvREADONLY($y,1);
1029tie $y, "";
1030
1031EXPECT
1032ok
1033Modification of a read-only value attempted at - line 16.
1034########
5a37a95f
FC
1035#
1036# And one should not be able to tie read-only COWs
1037for(__PACKAGE__) { tie $_, "" }
1038sub TIESCALAR {bless []}
1039EXPECT
1040Modification of a read-only value attempted at - line 3.
1041########
4be76e1f 1042
6dd7c1f1
FC
1043# Similarly, read-only regexps cannot be tied.
1044sub TIESCALAR { bless [] }
1045$y = ${qr//};
1046Internals::SvREADONLY($y,1);
1047tie $y, "";
1048
1049EXPECT
1050Modification of a read-only value attempted at - line 6.
1051########
1052
4be76e1f
FC
1053# tied() should still work on tied scalars after glob assignment
1054sub TIESCALAR {bless[]}
1055sub FETCH {*foo}
1056sub f::TIEHANDLE{bless[],f}
1057tie *foo, "f";
1058tie $rin, "";
1059[$rin]; # call FETCH
1060print ref tied $rin, "\n";
1061print ref tied *$rin, "\n";
1062EXPECT
1063main
1064f
8bb5f786
FC
1065########
1066
ca0d4ed9
FC
1067# (un)tie $glob_copy vs (un)tie *$glob_copy
1068sub TIESCALAR { print "TIESCALAR\n"; bless [] }
1069sub TIEHANDLE{ print "TIEHANDLE\n"; bless [] }
1070sub FETCH { print "never called\n" }
8bb5f786
FC
1071$f = *foo;
1072tie *$f, "";
1073tie $f, "";
ca0d4ed9
FC
1074untie $f;
1075print "ok 1\n" if !tied $f;
1076() = $f; # should not call FETCH
1077untie *$f;
1078print "ok 2\n" if !tied *foo;
8bb5f786
FC
1079EXPECT
1080TIEHANDLE
1081TIESCALAR
ca0d4ed9
FC
1082ok 1
1083ok 2
d8ef3a16
DM
1084########
1085
1086# RT #8611 mustn't goto outside the magic stack
1087sub TIESCALAR { warn "tiescalar\n"; bless [] }
1088sub FETCH { warn "fetch()\n"; goto FOO; }
1089tie $f, "";
1090warn "before fetch\n";
1091my $a = "$f";
1092warn "before FOO\n";
1093FOO:
1094warn "after FOO\n";
1095EXPECT
1096tiescalar
1097before fetch
1098fetch()
1099Can't find label FOO at - line 4.
1100########
1101
1102# RT #8611 mustn't goto outside the magic stack
1103sub TIEHANDLE { warn "tiehandle\n"; bless [] }
1104sub PRINT { warn "print()\n"; goto FOO; }
1105tie *F, "";
1106warn "before print\n";
1107print F "abc";
1108warn "before FOO\n";
1109FOO:
1110warn "after FOO\n";
1111EXPECT
1112tiehandle
1113before print
1114print()
1115Can't find label FOO at - line 4.
ff55a019
FC
1116########
1117
1118# \&$tied with $tied holding a reference before the fetch (but not after)
1119sub ::72 { 73 };
1120sub TIESCALAR {bless[]}
1121sub STORE{}
1122sub FETCH { 72 }
1123tie my $x, "main";
1124$x = \$y;
1125\&$x;
1126print "ok\n";
1127EXPECT
1128ok
1129########
1130
1131# \&$tied with $tied holding a PVLV glob before the fetch (but not after)
1132sub ::72 { 73 };
1133sub TIEARRAY {bless[]}
1134sub STORE{}
1135sub FETCH { 72 }
1136tie my @x, "main";
1137my $elem = \$x[0];
1138$$elem = *bar;
1139print &{\&$$elem}, "\n";
1140EXPECT
114173
48e092ec
FC
1142########
1143
1144# \&$tied with $tied holding a PVGV glob before the fetch (but not after)
1145local *72 = sub { 73 };
1146sub TIESCALAR {bless[]}
1147sub STORE{}
1148sub FETCH { 72 }
1149tie my $x, "main";
1150$x = *bar;
1151print &{\&$x}, "\n";
1152EXPECT
115373
9c3f0156
FC
1154########
1155
1156# Lexicals should not be visible to magic methods on scope exit
1157BEGIN { unless (defined &DynaLoader::boot_DynaLoader) {
1158 print "HASH\nHASH\nARRAY\nARRAY\n"; exit;
1159}}
1160use Scalar::Util 'weaken';
1161{ package xoufghd;
1162 sub TIEHASH { Scalar::Util::weaken($_[1]); bless \$_[1], xoufghd:: }
1163 *TIEARRAY = *TIEHASH;
1164 DESTROY {
1165 bless ${$_[0]} || return, 0;
1166} }
1167for my $sub (
1168 # hashes: ties before backrefs
1169 sub {
1170 my %hash;
1171 $ref = ref \%hash;
1172 tie %hash, xoufghd::, \%hash;
1173 1;
1174 },
1175 # hashes: backrefs before ties
1176 sub {
1177 my %hash;
1178 $ref = ref \%hash;
1179 weaken(my $x = \%hash);
1180 tie %hash, xoufghd::, \%hash;
1181 1;
1182 },
8be25b25 1183 # arrays: ties before backrefs
9c3f0156
FC
1184 sub {
1185 my @array;
1186 $ref = ref \@array;
1187 tie @array, xoufghd::, \@array;
1188 1;
1189 },
8be25b25 1190 # arrays: backrefs before ties
9c3f0156
FC
1191 sub {
1192 my @array;
1193 $ref = ref \@array;
1194 weaken(my $x = \@array);
1195 tie @array, xoufghd::, \@array;
1196 1;
1197 },
1198) {
1199 &$sub;
1200 &$sub;
1201 print $ref, "\n";
1202}
1203EXPECT
1204HASH
1205HASH
1206ARRAY
1207ARRAY
f1f99dc1
FC
1208########
1209
1210# Localising a tied variable with a typeglob in it should copy magic
1211sub TIESCALAR{bless[]}
1212sub FETCH{warn "fetching\n"; *foo}
1213sub STORE{}
1214tie $x, "";
1215local $x;
1216warn "before";
1217"$x";
1218warn "after";
1219EXPECT
1220fetching
1221before at - line 8.
1222fetching
1223after at - line 10.
dc456155
FC
1224########
1225
1226# tied returns same value as tie
1227sub TIESCALAR{bless[]}
1228$tyre = \tie $tied, "";
1229print "ok\n" if \tied $tied == $tyre;
1230EXPECT
1231ok
ce65bc73
FC
1232########
1233
1234# tied arrays should always be AvREAL
1235$^W=1;
1236sub TIEARRAY{bless[]}
1237sub {
1238 tie @_, "";
1239 \@_; # used to produce: av_reify called on tied array at - line 7.
1240}->(1);
1241EXPECT
4c13be3f
FC
1242########
1243
1244# [perl #67490] scalar-tying elements of magic hashes
1245sub TIESCALAR{bless[]}
1246sub STORE{}
1247tie $ENV{foo}, '';
1248$ENV{foo} = 78;
1249delete $ENV{foo};
1250tie $^H{foo}, '';
1251$^H{foo} = 78;
1252delete $^H{foo};
1253EXPECT
7e482323
FC
1254########
1255
1256# [perl #35865, #43011] autovivification should call FETCH after STORE
1257# because perl does not know that the FETCH would have returned the same
1258# thing that was just stored.
1259
1260# This package never likes to take ownership of other people’s refs. It
1261# always makes its own copies. (For simplicity, it only accepts hashes.)
1262package copier {
1263 sub TIEHASH { bless {} }
1264 sub FETCH { $_[0]{$_[1]} }
1265 sub STORE { $_[0]{$_[1]} = { %{ $_[2] } } }
1266}
1267tie my %h, copier::;
1268$h{i}{j} = 'k';
1269print $h{i}{j}, "\n";
1270EXPECT
1271k
760209f8
BF
1272########
1273
1274# [perl #8931] FETCH for tied $" called an odd number of times.
1275use strict;
1276my $i = 0;
1277sub A::TIESCALAR {bless [] => 'A'}
1278sub A::FETCH {print ++ $i, "\n"}
1279my @a = ("", "", "");
1280
1281tie $" => 'A';
1282"@a";
1283
1284$i = 0;
1285tie my $a => 'A';
1286join $a, 1..10;
1287EXPECT
12881
12891
8f9dd741
BF
1290########
1291
1292# [perl #9391] return value from 'tied' not discarded soon enough
1293use warnings;
1294tie @a, 'T';
1295if (tied @a) {
1296untie @a;
1297}
1298
1299sub T::TIEARRAY { my $s; bless \$s => "T" }
1300EXPECT
aec0c0cc 1301########
8f9dd741 1302
aec0c0cc
FC
1303# NAME Test that tying a hash does not leak a deleted iterator
1304# This produced unbalanced string table warnings under
1305# PERL_DESTRUCT_LEVEL=2.
1306package l {
1307 sub TIEHASH{bless[]}
1308}
1309$h = {foo=>0};
1310each %$h;
1311delete $$h{foo};
1312tie %$h, 'l';
1313EXPECT
0960ff5a
FC
1314########
1315
1316# NAME EXISTS on arrays
1317sub TIEARRAY{bless[]};
1318sub FETCHSIZE { 50 }
1319sub EXISTS { print "does $_[1] exist?\n" }
1320tie @a, "";
1321exists $a[1];
1322exists $a[-1];
1323$NEGATIVE_INDICES=1;
1324exists $a[-1];
1325EXPECT
1326does 1 exist?
1327does 49 exist?
1328does -1 exist?
ac9f75b5
FC
1329########
1330
1331# Crash when using negative index on array tied to non-object
1332sub TIEARRAY{bless[]};
1333${\tie @a, ""} = undef;
1334eval { $_ = $a[-1] }; print $@;
1335eval { $a[-1] = '' }; print $@;
1336eval { delete $a[-1] }; print $@;
1337eval { exists $a[-1] }; print $@;
1338
1339EXPECT
1340Can't call method "FETCHSIZE" on an undefined value at - line 5.
1341Can't call method "FETCHSIZE" on an undefined value at - line 6.
1342Can't call method "FETCHSIZE" on an undefined value at - line 7.
1343Can't call method "FETCHSIZE" on an undefined value at - line 8.
ff44333e
FC
1344########
1345
7274b33c
FC
1346# Crash when reading negative index when NEGATIVE_INDICES stub exists
1347sub NEGATIVE_INDICES;
1348sub TIEARRAY{bless[]};
1349sub FETCHSIZE{}
1350tie @a, "";
1351print "ok\n" if ! defined $a[-1];
1352EXPECT
1353ok
1354########
1355
ff44333e
FC
1356# Assigning vstrings to tied scalars
1357sub TIESCALAR{bless[]};
1358sub STORE { print ref \$_[1], "\n" }
1359tie $x, ""; $x = v3;
1360EXPECT
1361VSTRING
13733cde
FC
1362########
1363
1364# [perl #27010] Tying deferred elements
1365$\="\n";
1366sub TIESCALAR{bless[]};
1367sub {
1368 tie $_[0], "";
1369 print ref tied $h{k};
1370 tie $h{l}, "";
1371 print ref tied $_[1];
1372 untie $h{k};
1373 print tied $_[0] // 'undef';
1374 untie $_[1];
1375 print tied $h{l} // 'undef';
1376 # check that tied and untie do not autovivify
1377 # XXX should they autovivify?
1378 tied $_[2];
1379 print exists $h{m} ? "yes" : "no";
1380 untie $_[2];
1381 print exists $h{m} ? "yes" : "no";
1382}->($h{k}, $h{l}, $h{m});
1383EXPECT
1384main
1385main
1386undef
1387undef
1388no
1389no
2d885586
FC
1390########
1391
b479c9f2 1392# [perl #78194] Passing op return values to tie constructors
2d885586
FC
1393sub TIEARRAY{
1394 print \$_[1] == \$_[1] ? "ok\n" : "not ok\n";
1395};
1396tie @a, "", "$a$b";
1397EXPECT
1398ok
3805b5fb
FC
1399########
1400
1401# Scalar-tied locked hash keys and copy-on-write
1402use Tie::Scalar;
1403tie $h{foo}, Tie::StdScalar;
9ff3e6d8
FC
1404tie $h{bar}, Tie::StdScalar;
1405$h{foo} = __PACKAGE__; # COW
1406$h{bar} = 1; # not COW
3805b5fb
FC
1407# Moral equivalent of Hash::Util::lock_whatever, but miniperl-compatible
1408Internals::SvREADONLY($h{foo},1);
9ff3e6d8
FC
1409Internals::SvREADONLY($h{bar},1);
1410print $h{foo}, "\n"; # should not croak
1411# Whether the value is COW should make no difference here (whether the
1412# behaviour is ultimately correct is another matter):
1413local $h{foo};
1414local $h{bar};
1415print "ok\n" if (eval{ $h{foo} = 1 }||$@) eq (eval{ $h{bar} = 1 }||$@);
3805b5fb
FC
1416EXPECT
1417main
9ff3e6d8 1418ok
ad39f3a2
FC
1419########
1420
1421# &xsub and goto &xsub with tied @_
1422use Tie::Array;
1423tie @_, Tie::StdArray;
1424@_ = "\xff";
1425&utf8::encode;
1426printf "%x\n", $_ for map ord, split //, $_[0];
1427print "--\n";
1428@_ = "\xff";
1429& {sub { goto &utf8::encode }};
1430printf "%x\n", $_ for map ord, split //, $_[0];
1431EXPECT
1432c3
1433bf
1434--
1435c3
1436bf
ca58dfd9
FC
1437########
1438
1439# Defelem pointing to nonexistent element of tied array
1440
1441use Tie::Array;
1442# This sub is called with a deferred element. Inside the sub, $_[0] pros-
1443# pectively points to element 10000 of @a.
1444sub {
1445 tie @a, "Tie::StdArray"; # now @a is tied
1446 $#a = 20000; # and FETCHSIZE/AvFILL will now return a big number
1447 $a[10000] = "crumpets\n";
1448 $_ = "$_[0]"; # but defelems don’t expect tied arrays and try to read
1449 # AvARRAY[10000], which crashes
1450}->($a[10000]);
1451print
1452EXPECT
1453crumpets