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