This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
gv:gv_try_downgrade: Leave PL_stderrgv alone
[perl5.git] / t / op / magic.t
1 #!./perl
2
3 BEGIN {
4     $| = 1;
5     chdir 't' if -d 't';
6     @INC = '../lib';
7     require './test.pl';
8     plan (tests => 187);
9 }
10
11 # Test that defined() returns true for magic variables created on the fly,
12 # even before they have been created.
13 # This must come first, even before turning on warnings or setting up
14 # $SIG{__WARN__}, to avoid invalidating the tests.  warnings.pm currently
15 # does not mention any special variables, but that could easily change.
16 BEGIN {
17     # not available in miniperl
18     my %non_mini = map { $_ => 1 } qw(+ - [);
19     for (qw(
20         SIG ^OPEN ^TAINT ^UNICODE ^UTF8LOCALE ^WARNING_BITS 1 2 3 4 5 6 7 8
21         9 42 & ` ' : ? ! _ - [ ^ ~ = % . ( ) < > \ / $ | + ; ] ^A ^C ^D
22         ^E ^F ^H ^I ^L ^N ^O ^P ^S ^T ^V ^W ^UTF8CACHE ::12345 main::98732
23         ^LAST_FH
24     )) {
25         my $v = $_;
26         # avoid using any global vars here:
27         if ($v =~ s/^\^(?=.)//) {
28             for(substr $v, 0, 1) {
29                 $_ = chr ord() - 64;
30             }
31         }
32         SKIP:
33         {
34             skip_if_miniperl("the module for *$_ may not be available in "
35                              . "miniperl", 1) if $non_mini{$_};
36             ok defined *$v, "*$_ appears to be defined at the outset";
37         }
38     }
39 }
40
41 # This must be in a separate BEGIN block, as the mere mention of ${^TAINT}
42 # will invalidate the test for it.
43 BEGIN {
44     $ENV{PATH} = '/bin' if ${^TAINT};
45     $SIG{__WARN__} = sub { die "Dying on warning: ", @_ };
46 }
47
48 use warnings;
49 use Config;
50
51
52 $Is_MSWin32  = $^O eq 'MSWin32';
53 $Is_NetWare  = $^O eq 'NetWare';
54 $Is_VMS      = $^O eq 'VMS';
55 $Is_Dos      = $^O eq 'dos';
56 $Is_os2      = $^O eq 'os2';
57 $Is_Cygwin   = $^O eq 'cygwin';
58
59 $PERL =
60    ($Is_NetWare ? 'perl'   :
61     $Is_VMS     ? $^X      :
62     $Is_MSWin32 ? '.\perl' :
63                   './perl');
64
65 sub env_is {
66     my ($key, $val, $desc) = @_;
67
68     use open IN => ":raw";
69     if ($Is_MSWin32) {
70         # cmd.exe will echo 'variable=value' but 4nt will echo just the value
71         # -- Nikola Knezevic
72         require Win32;
73         my $cp = Win32::GetConsoleOutputCP();
74         Win32::SetConsoleOutputCP(Win32::GetACP());
75         (my $set = `set $key 2>nul`) =~ s/\r\n$/\n/;
76         Win32::SetConsoleOutputCP($cp);
77         like $set, qr/^(?:\Q$key\E=)?\Q$val\E$/, $desc;
78     } elsif ($Is_VMS) {
79         my $eqv = `write sys\$output f\$trnlnm("\Q$key\E")`;
80         # A single null byte in the equivalence string means
81         # an undef value for Perl, so mimic that here.
82         $eqv = "\n" if length($eqv) == 2 and $eqv eq "\000\n";
83         is $eqv, "$val\n", $desc;
84     } else {
85         chomp (my @env = grep { s/^$key=// } `env`);
86         is "@env", $val, $desc;
87     }
88 }
89
90 END {
91     # On VMS, environment variable changes are peristent after perl exits
92     if ($Is_VMS) {
93         delete $ENV{'FOO'};
94         delete $ENV{'__NoNeSuCh'};
95         delete $ENV{'__NoNeSuCh2'};
96     }
97 }
98
99 eval '$ENV{"FOO"} = "hi there";';       # check that ENV is inited inside eval
100 # cmd.exe will echo 'variable=value' but 4nt will echo just the value
101 # -- Nikola Knezevic
102 if ($Is_MSWin32)  { like `set FOO`, qr/^(?:FOO=)?hi there$/; }
103 elsif ($Is_VMS)   { is `write sys\$output f\$trnlnm("FOO")`, "hi there\n"; }
104 else              { is `echo \$FOO`, "hi there\n"; }
105
106 unlink_all 'ajslkdfpqjsjfk';
107 $! = 0;
108 open(FOO,'ajslkdfpqjsjfk');
109 isnt($!, 0);
110 close FOO; # just mention it, squelch used-only-once
111
112 SKIP: {
113     skip('SIGINT not safe on this platform', 5)
114         if $Is_MSWin32 || $Is_NetWare || $Is_Dos;
115   # the next tests are done in a subprocess because sh spits out a
116   # newline onto stderr when a child process kills itself with SIGINT.
117   # We use a pipe rather than system() because the VMS command buffer
118   # would overflow with a command that long.
119
120     # For easy interpolation of test numbers:
121     $next_test = curr_test() - 1;
122     sub TIEARRAY {bless[]}
123     sub FETCH { $next_test + pop }
124     tie my @tn, __PACKAGE__;
125
126     open( CMDPIPE, "| $PERL");
127
128     print CMDPIPE "\$t1 = $tn[1]; \$t2 = $tn[2];\n", <<'END';
129
130     $| = 1;             # command buffering
131
132     $SIG{"INT"} = "ok1";     kill "INT",$$; sleep 1;
133     $SIG{"INT"} = "IGNORE";  kill "INT",$$; sleep 1; print "ok $t2\n";
134     $SIG{"INT"} = "DEFAULT"; kill "INT",$$; sleep 1; print" not ok $t2\n";
135
136     sub ok1 {
137         if (($x = pop(@_)) eq "INT") {
138             print "ok $t1\n";
139         }
140         else {
141             print "not ok $t1 ($x @_)\n";
142         }
143     }
144
145 END
146
147     close CMDPIPE;
148
149     open( CMDPIPE, "| $PERL");
150     print CMDPIPE "\$t3 = $tn[3];\n", <<'END';
151
152     { package X;
153         sub DESTROY {
154             kill "INT",$$;
155         }
156     }
157     sub x {
158         my $x=bless [], 'X';
159         return sub { $x };
160     }
161     $| = 1;             # command buffering
162     $SIG{"INT"} = "ok3";
163     {
164         local $SIG{"INT"}=x();
165         print ""; # Needed to expose failure in 5.8.0 (why?)
166     }
167     sleep 1;
168     delete $SIG{"INT"};
169     kill "INT",$$; sleep 1;
170     sub ok3 {
171         print "ok $t3\n";
172     }
173 END
174     close CMDPIPE;
175     $? >>= 8 if $^O eq 'VMS'; # POSIX status hiding in 2nd byte
176     my $todo = ($^O eq 'os2' ? ' # TODO: EMX v0.9d_fix4 bug: wrong nibble? ' : '');
177     print $? & 0xFF ? "ok $tn[4]$todo\n" : "not ok $tn[4]$todo\n";
178
179     open(CMDPIPE, "| $PERL");
180     print CMDPIPE <<'END';
181
182     sub PVBM () { 'foo' }
183     index 'foo', PVBM;
184     my $pvbm = PVBM;
185
186     sub foo { exit 0 }
187
188     $SIG{"INT"} = $pvbm;
189     kill "INT", $$; sleep 1;
190 END
191     close CMDPIPE;
192     $? >>= 8 if $^O eq 'VMS';
193     print $? ? "not ok $tn[5]\n" : "ok $tn[5]\n";
194
195     curr_test(curr_test() + 5);
196 }
197
198 # can we slice ENV?
199 @val1 = @ENV{keys(%ENV)};
200 @val2 = values(%ENV);
201 is join(':',@val1), join(':',@val2);
202 cmp_ok @val1, '>', 1;
203
204 # deleting $::{ENV}
205 is runperl(prog => 'delete $::{ENV}; chdir; print qq-ok\n-'), "ok\n",
206   'deleting $::{ENV}';
207
208 # regex vars
209 'foobarbaz' =~ /b(a)r/;
210 is $`, 'foo';
211 is $&, 'bar';
212 is $', 'baz';
213 is $+, 'a';
214
215 # [perl #24237]
216 for (qw < ` & ' >) {
217  fresh_perl_is
218   qq < \@$_; q "fff" =~ /(?!^)./; print "[\$$_]\\n" >,
219   "[f]\n", {},
220   "referencing \@$_ before \$$_ etc. still saws off ampersands";
221 }
222
223 # $"
224 @a = qw(foo bar baz);
225 is "@a", "foo bar baz";
226 {
227     local $" = ',';
228     is "@a", "foo,bar,baz";
229 }
230
231 # $;
232 %h = ();
233 $h{'foo', 'bar'} = 1;
234 is((keys %h)[0], "foo\034bar");
235 {
236     local $; = 'x';
237     %h = ();
238     $h{'foo', 'bar'} = 1;
239     is((keys %h)[0], 'fooxbar');
240 }
241
242 # $?, $@, $$
243 system qq[$PERL "-I../lib" -e "use vmsish qw(hushed); exit(0)"];
244 is $?, 0;
245 system qq[$PERL "-I../lib" -e "use vmsish qw(hushed); exit(1)"];
246 isnt $?, 0;
247
248 eval { die "foo\n" };
249 is $@, "foo\n";
250
251 ok !*@{HASH}, 'no %@';
252
253 cmp_ok($$, '>', 0);
254 my $pid = $$;
255 eval { $$ = 42 };
256 is $$, 42, '$$ can be modified';
257 SKIP: {
258     skip "no fork", 1 unless $Config{d_fork};
259     (my $kidpid = open my $fh, "-|") // skip "cannot fork: $!", 1;
260     if($kidpid) { # parent
261         my $kiddollars = <$fh>;
262         close $fh or die "cannot close pipe from kid proc: $!";
263         is $kiddollars, $kidpid, '$$ is reset on fork';
264     }
265     else { # child
266         print $$;
267         $::NO_ENDING = 1; # silence "Looks like you only ran..."
268         exit;
269     }
270 }
271 $$ = $pid; # Tests below use $$
272
273 # $^X and $0
274 {
275     my $is_abs = $Config{d_procselfexe} || $Config{usekernprocpathname}
276       || $Config{usensgetexecutablepath};
277     if ($^O eq 'qnx') {
278         chomp($wd = `/usr/bin/fullpath -t`);
279     }
280     elsif($Is_Cygwin || $is_abs) {
281        # Cygwin turns the symlink into the real file
282        chomp($wd = `pwd`);
283        $wd =~ s#/t$##;
284        $wd =~ /(.*)/; $wd = $1; # untaint
285        if ($Is_Cygwin) {
286            $wd = Cygwin::win_to_posix_path(Cygwin::posix_to_win_path($wd, 1));
287        }
288     }
289     elsif($Is_os2) {
290        $wd = Cwd::sys_cwd();
291     }
292     else {
293         $wd = '.';
294     }
295     my $perl = $Is_VMS || $is_abs ? $^X : "$wd/perl";
296     my $headmaybe = '';
297     my $middlemaybe = '';
298     my $tailmaybe = '';
299     $script = "$wd/show-shebang";
300     if ($Is_MSWin32) {
301         chomp($wd = `cd`);
302         $wd =~ s|\\|/|g;
303         $perl = "$wd/perl.exe";
304         $script = "$wd/show-shebang.bat";
305         $headmaybe = <<EOH ;
306 \@rem ='
307 \@echo off
308 $perl -x \%0
309 goto endofperl
310 \@rem ';
311 EOH
312         $tailmaybe = <<EOT ;
313
314 __END__
315 :endofperl
316 EOT
317     }
318     elsif ($Is_os2) {
319       $script = "./show-shebang";
320     }
321     elsif ($Is_VMS) {
322       $script = "[]show-shebang";
323     }
324     elsif ($Is_Cygwin) {
325       $middlemaybe = <<'EOX'
326 $^X = Cygwin::win_to_posix_path(Cygwin::posix_to_win_path($^X, 1));
327 $0 = Cygwin::win_to_posix_path(Cygwin::posix_to_win_path($0, 1));
328 EOX
329     }
330     if ($^O eq 'os390' or $^O eq 'posix-bc') {  # no shebang
331         $headmaybe = <<EOH ;
332     eval 'exec ./perl -S \$0 \${1+"\$\@"}'
333         if 0;
334 EOH
335     }
336     $s1 = "\$^X is $perl, \$0 is $script\n";
337     ok open(SCRIPT, ">$script") or diag "Can't write to $script: $!";
338     ok print(SCRIPT $headmaybe . <<EOB . $middlemaybe . <<'EOF' . $tailmaybe) or diag $!;
339 #!$perl
340 EOB
341 print "\$^X is $^X, \$0 is $0\n";
342 EOF
343     ok close(SCRIPT) or diag $!;
344     ok chmod(0755, $script) or diag $!;
345     $_ = $Is_VMS ? `$perl $script` : `$script`;
346     s/\.exe//i if $Is_Dos or $Is_Cygwin or $Is_os2;
347     s{is perl}{is $perl}; # for systems where $^X is only a basename
348     s{\\}{/}g;
349     if ($Is_MSWin32 || $Is_os2) {
350         is uc $_, uc $s1;
351     } else {
352   SKIP:
353      {
354           skip "# TODO: Hit bug posix-2058; exec does not setup argv[0] correctly." if ($^O eq "vos");
355           is $_, $s1;
356      }
357     }
358     $_ = `$perl $script`;
359     s/\.exe//i if $Is_Dos or $Is_os2 or $Is_Cygwin;
360     s{\\}{/}g;
361     if ($Is_MSWin32 || $Is_os2) {
362         is uc $_, uc $s1;
363     } else {
364         is $_, $s1;
365     }
366     ok unlink($script) or diag $!;
367     # CHECK
368     # Could this be replaced with:
369     # unlink_all($script);
370 }
371
372 # $], $^O, $^T
373 cmp_ok $], '>=', 5.00319;
374 ok $^O;
375 cmp_ok $^T, '>', 850000000;
376
377 # Test change 25062 is working
378 my $orig_osname = $^O;
379 {
380 local $^I = '.bak';
381 is $^O, $orig_osname, 'Assigning $^I does not clobber $^O';
382 }
383 $^O = $orig_osname;
384
385 {
386     #RT #72422
387     foreach my $p (0, 1) {
388         fresh_perl_is(<<"EOP", '2 4 8', undef, "test \$^P = $p");
389 \$DB::single = 2;
390 \$DB::trace = 4;
391 \$DB::signal = 8;
392 \$^P = $p;
393 print "\$DB::single \$DB::trace \$DB::signal";
394 EOP
395     }
396 }
397
398 # Check that assigning to $0 on Linux sets the process name with both
399 # argv[0] assignment and by calling prctl()
400 {
401   SKIP: {
402     skip "We don't have prctl() here", 2 unless $Config{d_prctl_set_name};
403
404     # We don't really need these tests. prctl() is tested in the
405     # Kernel, but test it anyway for our sanity. If something doesn't
406     # work (like if the system doesn't have a ps(1) for whatever
407     # reason) just bail out gracefully.
408     my $maybe_ps = sub {
409         my ($cmd) = @_;
410         local ($?, $!);
411
412         no warnings;
413         my $res = `$cmd`;
414         skip "Couldn't shell out to '$cmd', returned code $?", 2 if $?;
415         return $res;
416     };
417
418     my $name = "Good Morning, Dave";
419     $0 = $name;
420
421     chomp(my $argv0 = $maybe_ps->("ps h $$"));
422     chomp(my $prctl = $maybe_ps->("ps hc $$"));
423
424     like($argv0, $name, "Set process name through argv[0] ($argv0)");
425     like($prctl, substr($name, 0, 15), "Set process name through prctl() ($prctl)");
426   }
427 }
428
429 {
430     my $ok = 1;
431     my $warn = '';
432     local $SIG{'__WARN__'} = sub { $ok = 0; $warn = join '', @_; $warn =~ s/\n$//; };
433     $! = undef;
434     local $TODO = $Is_VMS ? "'\$!=undef' does throw a warning" : '';
435     ok($ok, $warn);
436 }
437
438 SKIP: {
439     skip_if_miniperl("miniperl can't rely on loading %Errno", 2);
440    no warnings 'void';
441
442 # Make sure Errno hasn't been prematurely autoloaded
443
444    ok !keys %Errno::;
445
446 # Test auto-loading of Errno when %! is used
447
448    ok scalar eval q{
449       %!;
450       scalar %Errno::;
451    }, $@;
452 }
453
454 SKIP:  {
455     skip_if_miniperl("miniperl can't rely on loading %Errno", 2);
456     # Make sure that Errno loading doesn't clobber $!
457
458     undef %Errno::;
459     delete $INC{"Errno.pm"};
460
461     open(FOO, "nonesuch"); # Generate ENOENT
462     my %errs = %{"!"}; # Cause Errno.pm to be loaded at run-time
463     ok ${"!"}{ENOENT};
464
465     # Make sure defined(*{"!"}) before %! does not stop %! from working
466     is
467       runperl(
468         prog => 'BEGIN { defined *{q-!-} } print qq-ok\n- if tied %!',
469       ),
470      "ok\n",
471      'defined *{"!"} does not stop %! from working';
472 }
473
474 # Check that we don't auto-load packages
475 foreach (['powie::!', 'Errno'],
476          ['powie::+', 'Tie::Hash::NamedCapture']) {
477     my ($symbol, $package) = @$_;
478     SKIP: {
479         (my $extension = $package) =~ s|::|/|g;
480         skip "$package is statically linked", 2
481             if $Config{static_ext} =~ m|\b\Q$extension\E\b|;
482         foreach my $scalar_first ('', '$$symbol;') {
483             my $desc = qq{Referencing %{"$symbol"}};
484             $desc .= qq{ after mentioning \${"$symbol"}} if $scalar_first;
485             $desc .= " doesn't load $package";
486
487             fresh_perl_is(<<"EOP", 0, {}, $desc);
488 use strict qw(vars subs);
489 my \$symbol = '$symbol';
490 $scalar_first;
491 1 if %{\$symbol};
492 print scalar %${package}::;
493 EOP
494         }
495     }
496 }
497
498 is $^S, 0;
499 eval { is $^S,1 };
500 eval " BEGIN { ok ! defined \$^S } ";
501 is $^S, 0;
502
503 my $taint = ${^TAINT};
504 is ${^TAINT}, $taint;
505 eval { ${^TAINT} = 1 };
506 is ${^TAINT}, $taint;
507
508 # 5.6.1 had a bug: @+ and @- were not properly interpolated
509 # into double-quoted strings
510 # 20020414 mjd-perl-patch+@plover.com
511 "I like pie" =~ /(I) (like) (pie)/;
512 is "@-",  "0 0 2 7";
513 is "@+", "10 1 6 10";
514
515 # Tests for the magic get of $\
516 {
517     my $ok = 0;
518     # [perl #19330]
519     {
520         local $\ = undef;
521         $\++; $\++;
522         $ok = $\ eq 2;
523     }
524     ok $ok;
525     $ok = 0;
526     {
527         local $\ = "a\0b";
528         $ok = "a$\b" eq "aa\0bb";
529     }
530     ok $ok;
531 }
532
533 # Test for bug [perl #36434]
534 # Can not do this test on VMS, and SYMBIAN according to comments
535 # in mg.c/Perl_magic_clear_all_env()
536 SKIP: {
537     skip('Can\'t make assignment to \%ENV on this system', 3) if $Is_VMS;
538
539     local @ISA;
540     local %ENV;
541     # This used to be __PACKAGE__, but that causes recursive
542     #  inheritance, which is detected earlier now and broke
543     #  this test
544     eval { push @ISA, __FILE__ };
545     is $@, '', 'Push a constant on a magic array';
546     $@ and print "# $@";
547     eval { %ENV = (PATH => __PACKAGE__) };
548     is $@, '', 'Assign a constant to a magic hash';
549     $@ and print "# $@";
550     eval { my %h = qw(A B); %ENV = (PATH => (keys %h)[0]) };
551     is $@, '', 'Assign a shared key to a magic hash';
552     $@ and print "# $@";
553 }
554
555 # Tests for Perl_magic_clearsig
556 foreach my $sig (qw(__WARN__ INT)) {
557     $SIG{$sig} = lc $sig;
558     is $SIG{$sig}, 'main::' . lc $sig, "Can assign to $sig";
559     is delete $SIG{$sig}, 'main::' . lc $sig, "Can delete from $sig";
560     is $SIG{$sig}, undef, "$sig is now gone";
561     is delete $SIG{$sig}, undef, "$sig remains gone";
562 }
563
564 # And now one which doesn't exist;
565 {
566     no warnings 'signal';
567     $SIG{HUNGRY} = 'mmm, pie';
568 }
569 is $SIG{HUNGRY}, 'mmm, pie', 'Can assign to HUNGRY';
570 is delete $SIG{HUNGRY}, 'mmm, pie', 'Can delete from HUNGRY';
571 is $SIG{HUNGRY}, undef, "HUNGRY is now gone";
572 is delete $SIG{HUNGRY}, undef, "HUNGRY remains gone";
573
574 # Test deleting signals that we never set
575 foreach my $sig (qw(__DIE__ _BOGUS_HOOK KILL THIRSTY)) {
576     is $SIG{$sig}, undef, "$sig is not present";
577     is delete $SIG{$sig}, undef, "delete of $sig returns undef";
578 }
579
580 {
581     $! = 9999;
582     is int $!, 9999, q{[perl #72850] Core dump in bleadperl from perl -e '$! = 9999; $a = $!;'};
583
584 }
585
586 # %+ %-
587 SKIP: {
588     skip_if_miniperl("No XS in miniperl", 2);
589     # Make sure defined(*{"+"}) before %+ does not stop %+ from working
590     is
591       runperl(
592         prog => 'BEGIN { defined *{q-+-} } print qq-ok\n- if tied %+',
593       ),
594      "ok\n",
595      'defined *{"+"} does not stop %+ from working';
596     is
597       runperl(
598         prog => 'BEGIN { defined *{q=-=} } print qq-ok\n- if tied %-',
599       ),
600      "ok\n",
601      'defined *{"-"} does not stop %- from working';
602 }
603
604 SKIP: {
605     skip_if_miniperl("No XS in miniperl", 3);
606
607     for ( [qw( %- Tie::Hash::NamedCapture )], [qw( $[ arybase )],
608           [qw( %! Errno )] ) {
609         my ($var, $mod) = @$_;
610         my $modfile = $mod =~ s|::|/|gr . ".pm";
611         fresh_perl_is
612            qq 'sub UNIVERSAL::AUTOLOAD{}
613                $mod\::foo() if 0;
614                $var;
615                print "ok\\n" if \$INC{"$modfile"}',
616           "ok\n",
617            { switches => [ '-X' ] },
618           "$var still loads $mod when stash and UNIVERSAL::AUTOLOAD exist";
619     }
620 }
621
622 # ${^LAST_FH}
623 () = tell STDOUT;
624 is ${^LAST_FH}, \*STDOUT, '${^LAST_FH} after tell';
625 () = tell STDIN;
626 is ${^LAST_FH}, \*STDIN, '${^LAST_FH} after another tell';
627 {
628     my $fh = *STDOUT;
629     () = tell $fh;
630     is ${^LAST_FH}, \$fh, '${^LAST_FH} referencing lexical coercible glob';
631 }
632 # This also tests that ${^LAST_FH} is a weak reference:
633 is ${^LAST_FH}, undef, '${^LAST_FH} is undef when PL_last_in_gv is NULL';
634
635
636 # $|
637 fresh_perl_is 'print $| = ~$|', "1\n", {switches => ['-l']},
638  '[perl #4760] print $| = ~$|';
639 fresh_perl_is
640  'select f; undef *f; ${q/|/}; print STDOUT qq|ok\n|', "ok\n", {},
641  '[perl #115206] no crash when vivifying $| while *{+select}{IO} is undef';
642
643 # ${^OPEN} and $^H interaction
644 # Setting ${^OPEN} causes $^H to change, but setting $^H would only some-
645 # times make ${^OPEN} change, depending on whether it was in the same BEGIN
646 # block.  Don’t test actual values (subject to change); just test for
647 # consistency.
648 my @stuff;
649 eval '
650     BEGIN { ${^OPEN} = "a\0b"; $^H = 0;          push @stuff, ${^OPEN} }
651     BEGIN { ${^OPEN} = "a\0b"; $^H = 0 } BEGIN { push @stuff, ${^OPEN} }
652 1' or die $@;
653 is $stuff[0], $stuff[1], '$^H modifies ${^OPEN} consistently';
654
655 # deleting $::{"\cH"}
656 is runperl(prog => 'delete $::{qq-\cH-}; ${^OPEN}=foo; print qq-ok\n-'),
657   "ok\n",
658   'deleting $::{"\cH"}';
659
660 # Tests for some non-magic names:
661 is ${^MPE}, undef, '${^MPE} starts undefined';
662 is ++${^MPE}, 1, '${^MPE} can be incremented';
663
664 # This one used to behave as ${^MATCH} due to a missing break:
665 is ${^MPEN}, undef, '${^MPEN} starts undefined';
666 # This one used to croak due to that missing break:
667 is ++${^MPEN}, 1, '${^MPEN} can be incremented';
668
669 # ^^^^^^^^^ New tests go here ^^^^^^^^^
670
671 SKIP: {
672     skip("%ENV manipulations fail or aren't safe on $^O", 19)
673         if $Is_Dos;
674
675  SKIP: {
676         skip("clearing \%ENV is not safe when running under valgrind or on VMS")
677             if $ENV{PERL_VALGRIND} || $Is_VMS;
678
679             $PATH = $ENV{PATH};
680             $PDL = $ENV{PERL_DESTRUCT_LEVEL} || 0;
681             $ENV{foo} = "bar";
682             %ENV = ();
683             $ENV{PATH} = $PATH;
684             $ENV{PERL_DESTRUCT_LEVEL} = $PDL || 0;
685             if ($Is_MSWin32) {
686                 is `set foo 2>NUL`, "";
687             } else {
688                 is `echo \$foo`, "\n";
689             }
690         }
691
692         $ENV{__NoNeSuCh} = 'foo';
693         $0 = 'bar';
694         env_is(__NoNeSuCh => 'foo', 'setting $0 does not break %ENV');
695
696         $ENV{__NoNeSuCh2} = 'foo';
697         $ENV{__NoNeSuCh2} = undef;
698         env_is(__NoNeSuCh2 => '', 'setting a key as undef does not delete it');
699
700         # stringify a glob
701         $ENV{foo} = *TODO;
702         env_is(foo => '*main::TODO', 'ENV store of stringified glob');
703
704         # stringify a ref
705         my $ref = [];
706         $ENV{foo} = $ref;
707         env_is(foo => "$ref", 'ENV store of stringified ref');
708
709         # downgrade utf8 when possible
710         $bytes = "eh zero \x{A0}";
711         utf8::upgrade($chars = $bytes);
712         $forced = $ENV{foo} = $chars;
713         ok(!utf8::is_utf8($forced) && $forced eq $bytes, 'ENV store downgrades utf8 in SV');
714         env_is(foo => $bytes, 'ENV store downgrades utf8 in setenv');
715
716         # warn when downgrading utf8 is not possible
717         $chars = "X-Day \x{1998}";
718         utf8::encode($bytes = $chars);
719         {
720           my $warned = 0;
721           local $SIG{__WARN__} = sub { ++$warned if $_[0] =~ /^Wide character in setenv/; print "# @_" };
722           $forced = $ENV{foo} = $chars;
723           ok($warned == 1, 'ENV store warns about wide characters');
724         }
725         ok(!utf8::is_utf8($forced) && $forced eq $bytes, 'ENV store encodes high utf8 in SV');
726         env_is(foo => $bytes, 'ENV store encodes high utf8 in SV');
727
728         # test local $ENV{foo} on existing foo
729         {
730           local $ENV{__NoNeSuCh};
731           { local $TODO = 'exists on %ENV should reflect real env';
732             ok(!exists $ENV{__NoNeSuCh}, 'not exists $ENV{existing} during local $ENV{existing}'); }
733           env_is(__NoNeLoCaL => '');
734         }
735         ok(exists $ENV{__NoNeSuCh}, 'exists $ENV{existing} after local $ENV{existing}');
736         env_is(__NoNeSuCh => 'foo');
737
738         # test local $ENV{foo} on new foo
739         {
740           local $ENV{__NoNeLoCaL} = 'foo';
741           ok(exists $ENV{__NoNeLoCaL}, 'exists $ENV{new} during local $ENV{new}');
742           env_is(__NoNeLoCaL => 'foo');
743         }
744         ok(!exists $ENV{__NoNeLoCaL}, 'not exists $ENV{new} after local $ENV{new}');
745         env_is(__NoNeLoCaL => '');
746
747     SKIP: {
748             skip("\$0 check only on Linux and FreeBSD", 2)
749                 unless $^O =~ /^(linux|freebsd)$/
750                     && open CMDLINE, "/proc/$$/cmdline";
751
752             chomp(my $line = scalar <CMDLINE>);
753             my $me = (split /\0/, $line)[0];
754             is $me, $0, 'altering $0 is effective (testing with /proc/)';
755             close CMDLINE;
756             # perlbug #22811
757             my $mydollarzero = sub {
758               my($arg) = shift;
759               $0 = $arg if defined $arg;
760               # In FreeBSD the ps -o command= will cause
761               # an empty header line, grab only the last line.
762               my $ps = (`ps -o command= -p $$`)[-1];
763               return if $?;
764               chomp $ps;
765               printf "# 0[%s]ps[%s]\n", $0, $ps;
766               $ps;
767             };
768             my $ps = $mydollarzero->("x");
769             ok(!$ps  # we allow that something goes wrong with the ps command
770                # In Linux 2.4 we would get an exact match ($ps eq 'x') but
771                # in Linux 2.2 there seems to be something funny going on:
772                # it seems as if the original length of the argv[] would
773                # be stored in the proc struct and then used by ps(1),
774                # no matter what characters we use to pad the argv[].
775                # (And if we use \0:s, they are shown as spaces.)  Sigh.
776                || $ps =~ /^x\s*$/
777                # FreeBSD cannot get rid of both the leading "perl :"
778                # and the trailing " (perl)": some FreeBSD versions
779                # can get rid of the first one.
780                || ($^O eq 'freebsd' && $ps =~ m/^(?:perl: )?x(?: \(perl\))?$/),
781                        'altering $0 is effective (testing with `ps`)');
782         }
783 }
784
785 # test case-insignificance of %ENV (these tests must be enabled only
786 # when perl is compiled with -DENV_IS_CASELESS)
787 SKIP: {
788     skip('no caseless %ENV support', 4) unless $Is_MSWin32 || $Is_NetWare;
789
790     %ENV = ();
791     $ENV{'Foo'} = 'bar';
792     $ENV{'fOo'} = 'baz';
793     is scalar(keys(%ENV)), 1;
794     ok exists $ENV{'FOo'};
795     is delete $ENV{'foO'}, 'baz';
796     is scalar(keys(%ENV)), 0;
797 }
798
799 __END__
800
801 # Put new tests before the various ENV tests, as they blow %ENV away.