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.
17 # not available in miniperl
18 my %non_mini = map { $_ => 1 } 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
26 # avoid using any global vars here:
27 if ($v =~ s/^\^(?=.)//) {
28 for(substr $v, 0, 1) {
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";
41 # This must be in a separate BEGIN block, as the mere mention of ${^TAINT}
42 # will invalidate the test for it.
44 $ENV{PATH} = '/bin' if ${^TAINT};
45 $SIG{__WARN__} = sub { die "Dying on warning: ", @_ };
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';
60 ($Is_NetWare ? 'perl' :
62 $Is_MSWin32 ? '.\perl' :
66 my ($key, $val, $desc) = @_;
68 use open IN => ":raw";
70 # cmd.exe will echo 'variable=value' but 4nt will echo just the value
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;
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;
87 skip("env doesn't work on this android", 1) if !@env && $^O =~ /android/;
88 chomp (my @env = grep { s/^$key=// } @env);
89 is "@env", $val, $desc;
95 # On VMS, environment variable changes are peristent after perl exits
98 delete $ENV{'__NoNeSuCh'};
99 delete $ENV{'__NoNeSuCh2'};
103 eval '$ENV{"FOO"} = "hi there";'; # check that ENV is inited inside eval
104 # cmd.exe will echo 'variable=value' but 4nt will echo just the value
106 if ($Is_MSWin32) { like `set FOO`, qr/^(?:FOO=)?hi there$/; }
107 elsif ($Is_VMS) { is `write sys\$output f\$trnlnm("FOO")`, "hi there\n"; }
108 else { is `echo \$FOO`, "hi there\n"; }
110 unlink_all 'ajslkdfpqjsjfk';
112 open(FOO,'ajslkdfpqjsjfk');
113 isnt($!, 0, "Unlinked file can't be opened");
114 close FOO; # just mention it, squelch used-only-once
117 skip('SIGINT not safe on this platform', 5)
118 if $Is_MSWin32 || $Is_NetWare || $Is_Dos;
119 # the next tests are done in a subprocess because sh spits out a
120 # newline onto stderr when a child process kills itself with SIGINT.
121 # We use a pipe rather than system() because the VMS command buffer
122 # would overflow with a command that long.
124 # For easy interpolation of test numbers:
125 $next_test = curr_test() - 1;
126 sub TIEARRAY {bless[]}
127 sub FETCH { $next_test + pop }
128 tie my @tn, __PACKAGE__;
130 open( CMDPIPE, "|-", $PERL);
132 print CMDPIPE "\$t1 = $tn[1]; \$t2 = $tn[2];\n", <<'END';
134 $| = 1; # command buffering
136 $SIG{"INT"} = "ok1"; kill "INT",$$; sleep 1;
137 $SIG{"INT"} = "IGNORE"; kill "INT",$$; sleep 1; print "ok $t2\n";
138 $SIG{"INT"} = "DEFAULT"; kill "INT",$$; sleep 1; print" not ok $t2\n";
141 if (($x = pop(@_)) eq "INT") {
145 print "not ok $t1 ($x @_)\n";
153 open( CMDPIPE, "|-", $PERL);
154 print CMDPIPE "\$t3 = $tn[3];\n", <<'END';
165 $| = 1; # command buffering
168 local $SIG{"INT"}=x();
169 print ""; # Needed to expose failure in 5.8.0 (why?)
173 kill "INT",$$; sleep 1;
179 $? >>= 8 if $^O eq 'VMS'; # POSIX status hiding in 2nd byte
180 my $todo = ($^O eq 'os2' ? ' # TODO: EMX v0.9d_fix4 bug: wrong nibble? ' : '');
181 $todo = ($Config{usecrosscompile} ? '# TODO: Not sure whats going on here when cross-compiling' : '');
182 print $? & 0xFF ? "ok $tn[4]$todo\n" : "not ok $tn[4]$todo\n";
184 open(CMDPIPE, "|-", $PERL);
185 print CMDPIPE <<'END';
187 sub PVBM () { 'foo' }
194 kill "INT", $$; sleep 1;
197 $? >>= 8 if $^O eq 'VMS';
198 print $? ? "not ok $tn[5]\n" : "ok $tn[5]\n";
200 curr_test(curr_test() + 5);
204 @val1 = @ENV{keys(%ENV)};
205 @val2 = values(%ENV);
206 is join(':',@val1), join(':',@val2);
207 cmp_ok @val1, '>', 1;
210 is runperl(prog => 'delete $::{ENV}; chdir; print qq-ok\n-'), "ok\n",
214 'foobarbaz' =~ /b(a)r/;
223 qq < \@$_; q "fff" =~ /(?!^)./; print "[\$$_]\\n" >,
225 "referencing \@$_ before \$$_ etc. still saws off ampersands";
229 @a = qw(foo bar baz);
230 is "@a", "foo bar baz";
233 is "@a", "foo,bar,baz";
238 $h{'foo', 'bar'} = 1;
239 is((keys %h)[0], "foo\034bar");
243 $h{'foo', 'bar'} = 1;
244 is((keys %h)[0], 'fooxbar');
248 system qq[$PERL "-I../lib" -e "use vmsish qw(hushed); exit(0)"];
250 system qq[$PERL "-I../lib" -e "use vmsish qw(hushed); exit(1)"];
253 eval { die "foo\n" };
256 ok !*@{HASH}, 'no %@';
261 is $$, 42, '$$ can be modified';
263 skip "no fork", 1 unless $Config{d_fork};
264 (my $kidpid = open my $fh, "-|") // skip "cannot fork: $!", 1;
265 if($kidpid) { # parent
266 my $kiddollars = <$fh>;
267 close $fh or die "cannot close pipe from kid proc: $!";
268 is $kiddollars, $kidpid, '$$ is reset on fork';
272 $::NO_ENDING = 1; # silence "Looks like you only ran..."
276 $$ = $pid; # Tests below use $$
280 my $is_abs = $Config{d_procselfexe} || $Config{usekernprocpathname}
281 || $Config{usensgetexecutablepath};
283 chomp($wd = `/usr/bin/fullpath -t`);
285 elsif($^O =~ /android/) {
286 chomp($wd = `sh -c 'pwd'`);
288 elsif($Is_Cygwin || $is_abs) {
289 # Cygwin turns the symlink into the real file
292 $wd =~ /(.*)/; $wd = $1; # untaint
294 $wd = Cygwin::win_to_posix_path(Cygwin::posix_to_win_path($wd, 1));
298 $wd = Cwd::sys_cwd();
303 my $perl = $Is_VMS || $is_abs ? $^X : "$wd/perl";
305 my $middlemaybe = '';
307 $script = "$wd/show-shebang";
311 $perl = "$wd/perl.exe";
312 $script = "$wd/show-shebang.bat";
327 $script = "./show-shebang";
330 $script = "[]show-shebang";
333 $middlemaybe = <<'EOX'
334 $^X = Cygwin::win_to_posix_path(Cygwin::posix_to_win_path($^X, 1));
335 $0 = Cygwin::win_to_posix_path(Cygwin::posix_to_win_path($0, 1));
338 if ($^O eq 'os390' or $^O eq 'posix-bc') { # no shebang
340 eval 'exec ./perl -S \$0 \${1+"\$\@"}'
344 $s1 = "\$^X is $perl, \$0 is $script\n";
345 ok open(SCRIPT, ">$script") or diag "Can't write to $script: $!";
346 ok print(SCRIPT $headmaybe . <<EOB . $middlemaybe . <<'EOF' . $tailmaybe) or diag $!;
349 print "\$^X is $^X, \$0 is $0\n";
351 ok close(SCRIPT) or diag $!;
352 ok chmod(0755, $script) or diag $!;
353 $_ = $Is_VMS ? `$perl $script` : `$script`;
354 s/\.exe//i if $Is_Dos or $Is_Cygwin or $Is_os2;
355 s{is perl}{is $perl}; # for systems where $^X is only a basename
357 if ($Is_MSWin32 || $Is_os2) {
362 skip "# TODO: Hit bug posix-2058; exec does not setup argv[0] correctly." if ($^O eq "vos");
366 $_ = `$perl $script`;
367 s/\.exe//i if $Is_Dos or $Is_os2 or $Is_Cygwin;
369 if ($Is_MSWin32 || $Is_os2) {
374 ok unlink($script) or diag $!;
376 # Could this be replaced with:
377 # unlink_all($script);
381 cmp_ok $], '>=', 5.00319;
383 cmp_ok $^T, '>', 850000000;
385 # Test change 25062 is working
386 my $orig_osname = $^O;
389 is $^O, $orig_osname, 'Assigning $^I does not clobber $^O';
395 foreach my $p (0, 1) {
396 fresh_perl_is(<<"EOP", '2 4 8', undef, "test \$^P = $p");
401 print "\$DB::single \$DB::trace \$DB::signal";
406 # Check that assigning to $0 on Linux sets the process name with both
407 # argv[0] assignment and by calling prctl()
410 skip "We don't have prctl() here, or we're on Android", 2 unless $Config{d_prctl_set_name} && $^O ne 'android';
412 # We don't really need these tests. prctl() is tested in the
413 # Kernel, but test it anyway for our sanity. If something doesn't
414 # work (like if the system doesn't have a ps(1) for whatever
415 # reason) just bail out gracefully.
422 skip "Couldn't shell out to '$cmd', returned code $?", 2 if $?;
426 my $name = "Good Morning, Dave";
429 chomp(my $argv0 = $maybe_ps->("ps h $$"));
430 chomp(my $prctl = $maybe_ps->("ps hc $$"));
432 like($argv0, qr/$name/, "Set process name through argv[0] ($argv0)");
433 my $name_substr = substr($name, 0, 15);
434 like($prctl, qr/$name_substr/, "Set process name through prctl() ($prctl)");
441 local $SIG{'__WARN__'} = sub { $ok = 0; $warn = join '', @_; $warn =~ s/\n$//; };
443 local $TODO = $Is_VMS ? "'\$!=undef' does throw a warning" : '';
448 skip_if_miniperl("miniperl can't rely on loading %Errno", 2);
451 # Make sure Errno hasn't been prematurely autoloaded
455 # Test auto-loading of Errno when %! is used
464 skip_if_miniperl("miniperl can't rely on loading %Errno", 2);
465 # Make sure that Errno loading doesn't clobber $!
468 delete $INC{"Errno.pm"};
470 open(FOO, "nonesuch"); # Generate ENOENT
471 my %errs = %{"!"}; # Cause Errno.pm to be loaded at run-time
474 # Make sure defined(*{"!"}) before %! does not stop %! from working
477 prog => 'BEGIN { defined *{q-!-} } print qq-ok\n- if tied %!',
480 'defined *{"!"} does not stop %! from working';
483 # Check that we don't auto-load packages
484 foreach (['powie::!', 'Errno'],
485 ['powie::+', 'Tie::Hash::NamedCapture']) {
486 my ($symbol, $package) = @$_;
488 (my $extension = $package) =~ s|::|/|g;
489 skip "$package is statically linked", 2
490 if $Config{static_ext} =~ m|\b\Q$extension\E\b|;
491 foreach my $scalar_first ('', '$$symbol;') {
492 my $desc = qq{Referencing %{"$symbol"}};
493 $desc .= qq{ after mentioning \${"$symbol"}} if $scalar_first;
494 $desc .= " doesn't load $package";
496 fresh_perl_is(<<"EOP", 0, {}, $desc);
497 use strict qw(vars subs);
498 my \$symbol = '$symbol';
501 print scalar %${package}::;
509 eval " BEGIN { ok ! defined \$^S } ";
512 my $taint = ${^TAINT};
513 is ${^TAINT}, $taint;
514 eval { ${^TAINT} = 1 };
515 is ${^TAINT}, $taint;
517 # 5.6.1 had a bug: @+ and @- were not properly interpolated
518 # into double-quoted strings
519 # 20020414 mjd-perl-patch+@plover.com
520 "I like pie" =~ /(I) (like) (pie)/;
522 is "@+", "10 1 6 10";
524 # Tests for the magic get of $\
537 $ok = "a$\b" eq "aa\0bb";
542 # Test for bug [perl #36434]
543 # Can not do this test on VMS, and SYMBIAN according to comments
544 # in mg.c/Perl_magic_clear_all_env()
546 skip('Can\'t make assignment to \%ENV on this system', 3) if $Is_VMS;
550 # This used to be __PACKAGE__, but that causes recursive
551 # inheritance, which is detected earlier now and broke
553 eval { push @ISA, __FILE__ };
554 is $@, '', 'Push a constant on a magic array';
556 eval { %ENV = (PATH => __PACKAGE__) };
557 is $@, '', 'Assign a constant to a magic hash';
559 eval { my %h = qw(A B); %ENV = (PATH => (keys %h)[0]) };
560 is $@, '', 'Assign a shared key to a magic hash';
564 # Tests for Perl_magic_clearsig
565 foreach my $sig (qw(__WARN__ INT)) {
566 $SIG{$sig} = lc $sig;
567 is $SIG{$sig}, 'main::' . lc $sig, "Can assign to $sig";
568 is delete $SIG{$sig}, 'main::' . lc $sig, "Can delete from $sig";
569 is $SIG{$sig}, undef, "$sig is now gone";
570 is delete $SIG{$sig}, undef, "$sig remains gone";
573 # And now one which doesn't exist;
575 no warnings 'signal';
576 $SIG{HUNGRY} = 'mmm, pie';
578 is $SIG{HUNGRY}, 'mmm, pie', 'Can assign to HUNGRY';
579 is delete $SIG{HUNGRY}, 'mmm, pie', 'Can delete from HUNGRY';
580 is $SIG{HUNGRY}, undef, "HUNGRY is now gone";
581 is delete $SIG{HUNGRY}, undef, "HUNGRY remains gone";
583 # Test deleting signals that we never set
584 foreach my $sig (qw(__DIE__ _BOGUS_HOOK KILL THIRSTY)) {
585 is $SIG{$sig}, undef, "$sig is not present";
586 is delete $SIG{$sig}, undef, "delete of $sig returns undef";
591 is int $!, 9999, q{[perl #72850] Core dump in bleadperl from perl -e '$! = 9999; $a = $!;'};
597 skip_if_miniperl("No XS in miniperl", 2);
598 # Make sure defined(*{"+"}) before %+ does not stop %+ from working
601 prog => 'BEGIN { defined *{q-+-} } print qq-ok\n- if tied %+',
604 'defined *{"+"} does not stop %+ from working';
607 prog => 'BEGIN { defined *{q=-=} } print qq-ok\n- if tied %-',
610 'defined *{"-"} does not stop %- from working';
614 skip_if_miniperl("No XS in miniperl", 3);
616 for ( [qw( %- Tie::Hash::NamedCapture )], [qw( $[ arybase )],
618 my ($var, $mod) = @$_;
619 my $modfile = $mod =~ s|::|/|gr . ".pm";
621 qq 'sub UNIVERSAL::AUTOLOAD{}
624 print "ok\\n" if \$INC{"$modfile"}',
626 { switches => [ '-X' ] },
627 "$var still loads $mod when stash and UNIVERSAL::AUTOLOAD exist";
633 is ${^LAST_FH}, \*STDOUT, '${^LAST_FH} after tell';
635 is ${^LAST_FH}, \*STDIN, '${^LAST_FH} after another tell';
639 is ${^LAST_FH}, \$fh, '${^LAST_FH} referencing lexical coercible glob';
641 # This also tests that ${^LAST_FH} is a weak reference:
642 is ${^LAST_FH}, undef, '${^LAST_FH} is undef when PL_last_in_gv is NULL';
646 fresh_perl_is 'print $| = ~$|', "1\n", {switches => ['-l']},
647 '[perl #4760] print $| = ~$|';
649 'select f; undef *f; ${q/|/}; print STDOUT qq|ok\n|', "ok\n", {},
650 '[perl #115206] no crash when vivifying $| while *{+select}{IO} is undef';
652 # ${^OPEN} and $^H interaction
653 # Setting ${^OPEN} causes $^H to change, but setting $^H would only some-
654 # times make ${^OPEN} change, depending on whether it was in the same BEGIN
655 # block. Don’t test actual values (subject to change); just test for
659 BEGIN { ${^OPEN} = "a\0b"; $^H = 0; push @stuff, ${^OPEN} }
660 BEGIN { ${^OPEN} = "a\0b"; $^H = 0 } BEGIN { push @stuff, ${^OPEN} }
662 is $stuff[0], $stuff[1], '$^H modifies ${^OPEN} consistently';
664 # deleting $::{"\cH"}
665 is runperl(prog => 'delete $::{qq-\cH-}; ${^OPEN}=foo; print qq-ok\n-'),
667 'deleting $::{"\cH"}';
669 # Tests for some non-magic names:
670 is ${^MPE}, undef, '${^MPE} starts undefined';
671 is ++${^MPE}, 1, '${^MPE} can be incremented';
673 # This one used to behave as ${^MATCH} due to a missing break:
674 is ${^MPEN}, undef, '${^MPEN} starts undefined';
675 # This one used to croak due to that missing break:
676 is ++${^MPEN}, 1, '${^MPEN} can be incremented';
678 # ^^^^^^^^^ New tests go here ^^^^^^^^^
681 skip("%ENV manipulations fail or aren't safe on $^O", 19)
685 skip("clearing \%ENV is not safe when running under valgrind or on VMS")
686 if $ENV{PERL_VALGRIND} || $Is_VMS;
689 $PDL = $ENV{PERL_DESTRUCT_LEVEL} || 0;
693 $ENV{PERL_DESTRUCT_LEVEL} = $PDL || 0;
695 is `set foo 2>NUL`, "";
697 is `echo \$foo`, "\n";
701 $ENV{__NoNeSuCh} = 'foo';
703 env_is(__NoNeSuCh => 'foo', 'setting $0 does not break %ENV');
705 $ENV{__NoNeSuCh2} = 'foo';
706 $ENV{__NoNeSuCh2} = undef;
707 env_is(__NoNeSuCh2 => '', 'setting a key as undef does not delete it');
711 env_is(foo => '*main::TODO', 'ENV store of stringified glob');
716 env_is(foo => "$ref", 'ENV store of stringified ref');
718 # downgrade utf8 when possible
719 $bytes = "eh zero \x{A0}";
720 utf8::upgrade($chars = $bytes);
721 $forced = $ENV{foo} = $chars;
722 ok(!utf8::is_utf8($forced) && $forced eq $bytes, 'ENV store downgrades utf8 in SV');
723 env_is(foo => $bytes, 'ENV store downgrades utf8 in setenv');
725 # warn when downgrading utf8 is not possible
726 $chars = "X-Day \x{1998}";
727 utf8::encode($bytes = $chars);
730 local $SIG{__WARN__} = sub { ++$warned if $_[0] =~ /^Wide character in setenv/; print "# @_" };
731 $forced = $ENV{foo} = $chars;
732 ok($warned == 1, 'ENV store warns about wide characters');
734 ok(!utf8::is_utf8($forced) && $forced eq $bytes, 'ENV store encodes high utf8 in SV');
735 env_is(foo => $bytes, 'ENV store encodes high utf8 in SV');
737 # test local $ENV{foo} on existing foo
739 local $ENV{__NoNeSuCh};
740 { local $TODO = 'exists on %ENV should reflect real env';
741 ok(!exists $ENV{__NoNeSuCh}, 'not exists $ENV{existing} during local $ENV{existing}'); }
742 env_is(__NoNeLoCaL => '');
744 ok(exists $ENV{__NoNeSuCh}, 'exists $ENV{existing} after local $ENV{existing}');
745 env_is(__NoNeSuCh => 'foo');
747 # test local $ENV{foo} on new foo
749 local $ENV{__NoNeLoCaL} = 'foo';
750 ok(exists $ENV{__NoNeLoCaL}, 'exists $ENV{new} during local $ENV{new}');
751 env_is(__NoNeLoCaL => 'foo');
753 ok(!exists $ENV{__NoNeLoCaL}, 'not exists $ENV{new} after local $ENV{new}');
754 env_is(__NoNeLoCaL => '');
757 skip("\$0 check only on Linux and FreeBSD", 2)
758 unless $^O =~ /^(linux|android|freebsd)$/
759 && open CMDLINE, "/proc/$$/cmdline";
761 chomp(my $line = scalar <CMDLINE>);
762 my $me = (split /\0/, $line)[0];
763 is $me, $0, 'altering $0 is effective (testing with /proc/)';
765 skip("\$0 check with 'ps' only on Linux (but not Android) and FreeBSD", 1) if $^O eq 'android';
767 my $mydollarzero = sub {
769 $0 = $arg if defined $arg;
770 # In FreeBSD the ps -o command= will cause
771 # an empty header line, grab only the last line.
772 my $ps = (`ps -o command= -p $$`)[-1];
775 printf "# 0[%s]ps[%s]\n", $0, $ps;
778 my $ps = $mydollarzero->("x");
779 ok(!$ps # we allow that something goes wrong with the ps command
780 # In Linux 2.4 we would get an exact match ($ps eq 'x') but
781 # in Linux 2.2 there seems to be something funny going on:
782 # it seems as if the original length of the argv[] would
783 # be stored in the proc struct and then used by ps(1),
784 # no matter what characters we use to pad the argv[].
785 # (And if we use \0:s, they are shown as spaces.) Sigh.
787 # FreeBSD cannot get rid of both the leading "perl :"
788 # and the trailing " (perl)": some FreeBSD versions
789 # can get rid of the first one.
790 || ($^O eq 'freebsd' && $ps =~ m/^(?:perl: )?x(?: \(perl\))?$/),
791 'altering $0 is effective (testing with `ps`)');
795 # test case-insignificance of %ENV (these tests must be enabled only
796 # when perl is compiled with -DENV_IS_CASELESS)
798 skip('no caseless %ENV support', 4) unless $Is_MSWin32 || $Is_NetWare;
803 is scalar(keys(%ENV)), 1;
804 ok exists $ENV{'FOo'};
805 is delete $ENV{'foO'}, 'baz';
806 is scalar(keys(%ENV)), 0;
811 # Put new tests before the various ENV tests, as they blow %ENV away.