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