xref: /openbsd/gnu/usr.bin/perl/t/op/undef.t (revision 404b540a)
1#!./perl
2
3BEGIN {
4    chdir 't' if -d 't';
5    @INC = '../lib';
6    require './test.pl';
7}
8
9use strict;
10
11use vars qw(@ary %ary %hash);
12
13plan 37;
14
15ok !defined($a);
16
17$a = 1+1;
18ok defined($a);
19
20undef $a;
21ok !defined($a);
22
23$a = "hi";
24ok defined($a);
25
26$a = $b;
27ok !defined($a);
28
29@ary = ("1arg");
30$a = pop(@ary);
31ok defined($a);
32$a = pop(@ary);
33ok !defined($a);
34
35@ary = ("1arg");
36$a = shift(@ary);
37ok defined($a);
38$a = shift(@ary);
39ok !defined($a);
40
41$ary{'foo'} = 'hi';
42ok defined($ary{'foo'});
43ok !defined($ary{'bar'});
44undef $ary{'foo'};
45ok !defined($ary{'foo'});
46
47ok defined(@ary);
48ok defined(%ary);
49undef @ary;
50ok !defined(@ary);
51undef %ary;
52ok !defined(%ary);
53@ary = (1);
54ok defined @ary;
55%ary = (1,1);
56ok defined %ary;
57
58sub foo { pass; 1 }
59
60&foo || fail;
61
62ok defined &foo;
63undef &foo;
64ok !defined(&foo);
65
66eval { undef $1 };
67like $@, qr/^Modification of a read/;
68
69eval { $1 = undef };
70like $@, qr/^Modification of a read/;
71
72{
73    require Tie::Hash;
74    tie my %foo, 'Tie::StdHash';
75    ok defined %foo;
76    %foo = ( a => 1 );
77    ok defined %foo;
78}
79
80{
81    require Tie::Array;
82    tie my @foo, 'Tie::StdArray';
83    ok defined @foo;
84    @foo = ( a => 1 );
85    ok defined @foo;
86}
87
88{
89    # [perl #17753] segfault when undef'ing unquoted string constant
90    eval 'undef tcp';
91    like $@, qr/^Can't modify constant item/;
92}
93
94# bugid 3096
95# undefing a hash may free objects with destructors that then try to
96# modify the hash. To them, the hash should appear empty.
97
98%hash = (
99    key1 => bless({}, 'X'),
100    key2 => bless({}, 'X'),
101);
102undef %hash;
103sub X::DESTROY {
104    is scalar keys %hash, 0;
105    is scalar values %hash, 0;
106    my @l = each %hash;
107    is @l, 0;
108    is delete $hash{'key2'}, undef;
109}
110
111# this will segfault if it fails
112
113sub PVBM () { 'foo' }
114{ my $dummy = index 'foo', PVBM }
115
116my $pvbm = PVBM;
117undef $pvbm;
118ok !defined $pvbm;
119