This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Teach t/TEST about Math-BigInt in dist/
[perl5.git] / t / op / magic.t
1 #!./perl
2
3 BEGIN {
4     $| = 1;
5     chdir 't' if -d 't';
6     @INC = '../lib';
7     $ENV{PATH} = '/bin' if ${^TAINT};
8     $SIG{__WARN__} = sub { die "Dying on warning: ", @_ };
9     require './test.pl';
10 }
11
12 use warnings;
13 use Config;
14
15 plan (tests => 85);
16
17 $Is_MSWin32  = $^O eq 'MSWin32';
18 $Is_NetWare  = $^O eq 'NetWare';
19 $Is_VMS      = $^O eq 'VMS';
20 $Is_Dos      = $^O eq 'dos';
21 $Is_os2      = $^O eq 'os2';
22 $Is_Cygwin   = $^O eq 'cygwin';
23 $Is_MPE      = $^O eq 'mpeix';          
24 $Is_miniperl = $ENV{PERL_CORE_MINITEST};
25 $Is_BeOS     = $^O eq 'beos';
26
27 $PERL = $ENV{PERL}
28     || ($Is_NetWare           ? 'perl'   :
29        $Is_VMS                ? $^X      :
30        $Is_MSWin32            ? '.\perl' :
31        './perl');
32
33 END {
34     # On VMS, environment variable changes are peristent after perl exits
35     delete $ENV{'FOO'} if $Is_VMS;
36 }
37
38 eval '$ENV{"FOO"} = "hi there";';       # check that ENV is inited inside eval
39 # cmd.exe will echo 'variable=value' but 4nt will echo just the value
40 # -- Nikola Knezevic
41 if ($Is_MSWin32)  { like `set FOO`, qr/^(?:FOO=)?hi there$/; }
42 elsif ($Is_VMS)   { is `write sys\$output f\$trnlnm("FOO")`, "hi there\n"; }
43 else              { is `echo \$FOO`, "hi there\n"; }
44
45 unlink 'ajslkdfpqjsjfk';
46 $! = 0;
47 open(FOO,'ajslkdfpqjsjfk');
48 isnt($!, 0);
49 close FOO; # just mention it, squelch used-only-once
50
51 SKIP: {
52     skip('SIGINT not safe on this platform', 5)
53         if $Is_MSWin32 || $Is_NetWare || $Is_Dos || $Is_MPE;
54   # the next tests are done in a subprocess because sh spits out a
55   # newline onto stderr when a child process kills itself with SIGINT.
56   # We use a pipe rather than system() because the VMS command buffer
57   # would overflow with a command that long.
58
59     open( CMDPIPE, "| $PERL");
60
61     print CMDPIPE <<'END';
62
63     $| = 1;             # command buffering
64
65     $SIG{"INT"} = "ok3";     kill "INT",$$; sleep 1;
66     $SIG{"INT"} = "IGNORE";  kill "INT",$$; sleep 1; print "ok 4\n";
67     $SIG{"INT"} = "DEFAULT"; kill "INT",$$; sleep 1; print "not ok 4\n";
68
69     sub ok3 {
70         if (($x = pop(@_)) eq "INT") {
71             print "ok 3\n";
72         }
73         else {
74             print "not ok 3 ($x @_)\n";
75         }
76     }
77
78 END
79
80     close CMDPIPE;
81
82     open( CMDPIPE, "| $PERL");
83     print CMDPIPE <<'END';
84
85     { package X;
86         sub DESTROY {
87             kill "INT",$$;
88         }
89     }
90     sub x {
91         my $x=bless [], 'X';
92         return sub { $x };
93     }
94     $| = 1;             # command buffering
95     $SIG{"INT"} = "ok5";
96     {
97         local $SIG{"INT"}=x();
98         print ""; # Needed to expose failure in 5.8.0 (why?)
99     }
100     sleep 1;
101     delete $SIG{"INT"};
102     kill "INT",$$; sleep 1;
103     sub ok5 {
104         print "ok 5\n";
105     }
106 END
107     close CMDPIPE;
108     $? >>= 8 if $^O eq 'VMS'; # POSIX status hiding in 2nd byte
109     my $todo = ($^O eq 'os2' ? ' # TODO: EMX v0.9d_fix4 bug: wrong nibble? ' : '');
110     print $? & 0xFF ? "ok 6$todo\n" : "not ok 6$todo\n";
111
112     open(CMDPIPE, "| $PERL");
113     print CMDPIPE <<'END';
114
115     sub PVBM () { 'foo' }
116     index 'foo', PVBM;
117     my $pvbm = PVBM;
118
119     sub foo { exit 0 }
120
121     $SIG{"INT"} = $pvbm;
122     kill "INT", $$; sleep 1;
123 END
124     close CMDPIPE;
125     $? >>= 8 if $^O eq 'VMS';
126     print $? ? "not ok 7\n" : "ok 7\n";
127
128     curr_test(curr_test() + 5);
129 }
130
131 # can we slice ENV?
132 @val1 = @ENV{keys(%ENV)};
133 @val2 = values(%ENV);
134 is join(':',@val1), join(':',@val2);
135 cmp_ok @val1, '>', 1;
136
137 # regex vars
138 'foobarbaz' =~ /b(a)r/;
139 is $`, 'foo';
140 is $&, 'bar';
141 is $', 'baz';
142 is $+, 'a';
143
144 # $"
145 @a = qw(foo bar baz);
146 is "@a", "foo bar baz";
147 {
148     local $" = ',';
149     is "@a", "foo,bar,baz";
150 }
151
152 # $;
153 %h = ();
154 $h{'foo', 'bar'} = 1;
155 is((keys %h)[0], "foo\034bar");
156 {
157     local $; = 'x';
158     %h = ();
159     $h{'foo', 'bar'} = 1;
160     is((keys %h)[0], 'fooxbar');
161 }
162
163 # $?, $@, $$
164 system qq[$PERL "-I../lib" -e "use vmsish qw(hushed); exit(0)"];
165 is $?, 0;
166 system qq[$PERL "-I../lib" -e "use vmsish qw(hushed); exit(1)"];
167 isnt $?, 0;
168
169 eval { die "foo\n" };
170 is $@, "foo\n";
171
172 cmp_ok($$, '>', 0);
173 eval { $$++ };
174 like ($@, qr/^Modification of a read-only value attempted/);
175
176 # $^X and $0
177 {
178     if ($^O eq 'qnx') {
179         chomp($wd = `/usr/bin/fullpath -t`);
180     }
181     elsif($Is_Cygwin || $Config{'d_procselfexe'}) {
182        # Cygwin turns the symlink into the real file
183        chomp($wd = `pwd`);
184        $wd =~ s#/t$##;
185        $wd =~ /(.*)/; $wd = $1; # untaint
186        if ($Is_Cygwin) {
187            $wd = Cygwin::win_to_posix_path(Cygwin::posix_to_win_path($wd, 1));
188        }
189     }
190     elsif($Is_os2) {
191        $wd = Cwd::sys_cwd();
192     }
193     else {
194         $wd = '.';
195     }
196     my $perl = $Is_VMS ? $^X : "$wd/perl";
197     my $headmaybe = '';
198     my $middlemaybe = '';
199     my $tailmaybe = '';
200     $script = "$wd/show-shebang";
201     if ($Is_MSWin32) {
202         chomp($wd = `cd`);
203         $wd =~ s|\\|/|g;
204         $perl = "$wd/perl.exe";
205         $script = "$wd/show-shebang.bat";
206         $headmaybe = <<EOH ;
207 \@rem ='
208 \@echo off
209 $perl -x \%0
210 goto endofperl
211 \@rem ';
212 EOH
213         $tailmaybe = <<EOT ;
214
215 __END__
216 :endofperl
217 EOT
218     }
219     elsif ($Is_os2) {
220       $script = "./show-shebang";
221     }
222     elsif ($Is_VMS) {
223       $script = "[]show-shebang";
224     }
225     elsif ($Is_Cygwin) {
226       $middlemaybe = <<'EOX'
227 $^X = Cygwin::win_to_posix_path(Cygwin::posix_to_win_path($^X, 1));
228 $0 = Cygwin::win_to_posix_path(Cygwin::posix_to_win_path($0, 1));
229 EOX
230     }
231     if ($^O eq 'os390' or $^O eq 'posix-bc' or $^O eq 'vmesa') {  # no shebang
232         $headmaybe = <<EOH ;
233     eval 'exec ./perl -S \$0 \${1+"\$\@"}'
234         if 0;
235 EOH
236     }
237     $s1 = "\$^X is $perl, \$0 is $script\n";
238     ok open(SCRIPT, ">$script") or diag "Can't write to $script: $!";
239     ok print(SCRIPT $headmaybe . <<EOB . $middlemaybe . <<'EOF' . $tailmaybe) or diag $!;
240 #!$wd/perl
241 EOB
242 print "\$^X is $^X, \$0 is $0\n";
243 EOF
244     ok close(SCRIPT) or diag $!;
245     ok chmod(0755, $script) or diag $!;
246     $_ = $Is_VMS ? `$perl $script` : `$script`;
247     s/\.exe//i if $Is_Dos or $Is_Cygwin or $Is_os2;
248     s{./$script}{$script} if $Is_BeOS; # revert BeOS execvp() side-effect
249     s{\bminiperl\b}{perl}; # so that test doesn't fail with miniperl
250     s{is perl}{is $perl}; # for systems where $^X is only a basename
251     s{\\}{/}g;
252     if ($Is_MSWin32 || $Is_os2) {
253         is uc $_, uc $s1;
254     } else {
255         is $_, $s1;
256     }
257     $_ = `$perl $script`;
258     s/\.exe//i if $Is_Dos or $Is_os2 or $Is_Cygwin;
259     s{./$perl}{$perl} if $Is_BeOS; # revert BeOS execvp() side-effect
260     s{\\}{/}g;
261     if ($Is_MSWin32 || $Is_os2) {
262         is uc $_, uc $s1;
263     } else {
264         is $_, $s1;
265     }
266     ok unlink($script) or diag $!;
267 }
268
269 # $], $^O, $^T
270 cmp_ok $], '>=', 5.00319;
271 ok $^O;
272 cmp_ok $^T, '>', 850000000;
273
274 # Test change 25062 is working
275 my $orig_osname = $^O;
276 {
277 local $^I = '.bak';
278 is $^O, $orig_osname, 'Assigning $^I does not clobber $^O';
279 }
280 $^O = $orig_osname;
281
282 {
283     #RT #72422
284     foreach my $p (0, 1) {
285         fresh_perl_is(<<"EOP", '2 4 8', undef, "test \$^P = $p");
286 \$DB::single = 2;
287 \$DB::trace = 4;
288 \$DB::signal = 8;
289 \$^P = $p;
290 print "\$DB::single \$DB::trace \$DB::signal";
291 EOP
292     }
293 }
294
295 SKIP: {
296     skip("%ENV manipulations fail or aren't safe on $^O", 4)
297         if $Is_VMS || $Is_Dos;
298
299  SKIP: {
300         skip("clearing \%ENV is not safe when running under valgrind")
301             if $ENV{PERL_VALGRIND};
302
303             $PATH = $ENV{PATH};
304             $PDL = $ENV{PERL_DESTRUCT_LEVEL} || 0;
305             $ENV{foo} = "bar";
306             %ENV = ();
307             $ENV{PATH} = $PATH;
308             $ENV{PERL_DESTRUCT_LEVEL} = $PDL || 0;
309             if ($Is_MSWin32) {
310                 is `set foo 2>NUL`, "";
311             } else {
312                 is `echo \$foo`, "\n";
313             }
314         }
315
316         $ENV{__NoNeSuCh} = "foo";
317         $0 = "bar";
318 # cmd.exe will echo 'variable=value' but 4nt will echo just the value
319 # -- Nikola Knezevic
320         if ($Is_MSWin32) {
321             like `set __NoNeSuCh`, qr/^(?:__NoNeSuCh=)?foo$/;
322         } else {
323             is `echo \$__NoNeSuCh`, "foo\n";
324         }
325     SKIP: {
326             skip("\$0 check only on Linux and FreeBSD", 2)
327                 unless $^O =~ /^(linux|freebsd)$/
328                     && open CMDLINE, "/proc/$$/cmdline";
329
330             chomp(my $line = scalar <CMDLINE>);
331             my $me = (split /\0/, $line)[0];
332             is $me, $0, 'altering $0 is effective (testing with /proc/)';
333             close CMDLINE;
334             # perlbug #22811
335             my $mydollarzero = sub {
336               my($arg) = shift;
337               $0 = $arg if defined $arg;
338               # In FreeBSD the ps -o command= will cause
339               # an empty header line, grab only the last line.
340               my $ps = (`ps -o command= -p $$`)[-1];
341               return if $?;
342               chomp $ps;
343               printf "# 0[%s]ps[%s]\n", $0, $ps;
344               $ps;
345             };
346             my $ps = $mydollarzero->("x");
347             ok(!$ps  # we allow that something goes wrong with the ps command
348                # In Linux 2.4 we would get an exact match ($ps eq 'x') but
349                # in Linux 2.2 there seems to be something funny going on:
350                # it seems as if the original length of the argv[] would
351                # be stored in the proc struct and then used by ps(1),
352                # no matter what characters we use to pad the argv[].
353                # (And if we use \0:s, they are shown as spaces.)  Sigh.
354                || $ps =~ /^x\s*$/
355                # FreeBSD cannot get rid of both the leading "perl :"
356                # and the trailing " (perl)": some FreeBSD versions
357                # can get rid of the first one.
358                || ($^O eq 'freebsd' && $ps =~ m/^(?:perl: )?x(?: \(perl\))?$/),
359                        'altering $0 is effective (testing with `ps`)');
360         }
361 }
362
363 # Check that assigning to $0 on Linux sets the process name with both
364 # argv[0] assignment and by calling prctl()
365 {
366   SKIP: {
367     skip "We don't have prctl() here", 2 unless $Config{d_prctl_set_name};
368
369     # We don't really need these tests. prctl() is tested in the
370     # Kernel, but test it anyway for our sanity. If something doesn't
371     # work (like if the system doesn't have a ps(1) for whatever
372     # reason) just bail out gracefully.
373     my $maybe_ps = sub {
374         my ($cmd) = @_;
375         local ($?, $!);
376
377         no warnings;
378         my $res = `$cmd`;
379         skip "Couldn't shell out to `$cmd', returned code $?", 2 if $?;
380         return $res;
381     };
382
383     my $name = "Good Morning, Dave";
384     $0 = $name;
385
386     chomp(my $argv0 = $maybe_ps->("ps h $$"));
387     chomp(my $prctl = $maybe_ps->("ps hc $$"));
388
389     like($argv0, $name, "Set process name through argv[0] ($argv0)");
390     like($prctl, substr($name, 0, 15), "Set process name through prctl() ($prctl)");
391   }
392 }
393
394 {
395     my $ok = 1;
396     my $warn = '';
397     local $SIG{'__WARN__'} = sub { $ok = 0; $warn = join '', @_; $warn =~ s/\n$//; };
398     $! = undef;
399     local $TODO = $Is_VMS ? "'\$!=undef' does throw a warning" : '';
400     ok($ok, $warn);
401 }
402
403 # test case-insignificance of %ENV (these tests must be enabled only
404 # when perl is compiled with -DENV_IS_CASELESS)
405 SKIP: {
406     skip('no caseless %ENV support', 4) unless $Is_MSWin32 || $Is_NetWare;
407
408     %ENV = ();
409     $ENV{'Foo'} = 'bar';
410     $ENV{'fOo'} = 'baz';
411     is scalar(keys(%ENV)), 1;
412     ok exists $ENV{'FOo'};
413     is delete $ENV{'foO'}, 'baz';
414     is scalar(keys(%ENV)), 0;
415 }
416
417 SKIP: {
418     skip ("miniperl can't rely on loading %Errno", 2) if $Is_miniperl;
419    no warnings 'void';
420
421 # Make sure Errno hasn't been prematurely autoloaded
422
423    ok !keys %Errno::;
424
425 # Test auto-loading of Errno when %! is used
426
427    ok scalar eval q{
428       %!;
429       scalar %Errno::;
430    }, $@;
431 }
432
433 SKIP:  {
434     skip ("miniperl can't rely on loading %Errno") if $Is_miniperl;
435     # Make sure that Errno loading doesn't clobber $!
436
437     undef %Errno::;
438     delete $INC{"Errno.pm"};
439
440     open(FOO, "nonesuch"); # Generate ENOENT
441     my %errs = %{"!"}; # Cause Errno.pm to be loaded at run-time
442     ok ${"!"}{ENOENT};
443 }
444
445 is $^S, 0;
446 eval { is $^S,1 };
447 eval " BEGIN { ok ! defined \$^S } ";
448 is $^S, 0;
449
450 my $taint = ${^TAINT};
451 is ${^TAINT}, $taint;
452 eval { ${^TAINT} = 1 };
453 is ${^TAINT}, $taint;
454
455 # 5.6.1 had a bug: @+ and @- were not properly interpolated
456 # into double-quoted strings
457 # 20020414 mjd-perl-patch+@plover.com
458 "I like pie" =~ /(I) (like) (pie)/;
459 is "@-",  "0 0 2 7";
460 is "@+", "10 1 6 10";
461
462 # Tests for the magic get of $\
463 {
464     my $ok = 0;
465     # [perl #19330]
466     {
467         local $\ = undef;
468         $\++; $\++;
469         $ok = $\ eq 2;
470     }
471     ok $ok;
472     $ok = 0;
473     {
474         local $\ = "a\0b";
475         $ok = "a$\b" eq "aa\0bb";
476     }
477     ok $ok;
478 }
479
480 # Test for bug [perl #27839]
481 {
482     my $x;
483     sub f {
484         "abc" =~ /(.)./;
485         $x = "@+";
486         return @+;
487     };
488     "pqrstuvwxyz" =~ /..(....)../; # prime @+ etc in this scope
489     my @y = f();
490     is $x, "@y", "return a magic array ($x) vs (@y)";
491
492     sub f2 {
493         "abc" =~ /(?<foo>.)./;
494         my @h =  %+;
495         $x = "@h";
496         return %+;
497     };
498     @y = f();
499     is $x, "@y", "return a magic hash ($x) vs (@y)";
500 }
501
502 # Test for bug [perl #36434]
503 # Can not do this test on VMS, EPOC, and SYMBIAN according to comments
504 # in mg.c/Perl_magic_clear_all_env()
505 SKIP: {
506     skip('Can\'t make assignment to \%ENV on this system', 3) if $Is_VMS;
507
508     local @ISA;
509     local %ENV;
510     # This used to be __PACKAGE__, but that causes recursive
511     #  inheritance, which is detected earlier now and broke
512     #  this test
513     eval { push @ISA, __FILE__ };
514     is $@, '', 'Push a constant on a magic array';
515     $@ and print "# $@";
516     eval { %ENV = (PATH => __PACKAGE__) };
517     is $@, '', 'Assign a constant to a magic hash';
518     $@ and print "# $@";
519     eval { my %h = qw(A B); %ENV = (PATH => (keys %h)[0]) };
520     is $@, '', 'Assign a shared key to a magic hash';
521     $@ and print "# $@";
522 }
523
524 # Tests for Perl_magic_clearsig
525 foreach my $sig (qw(__WARN__ INT)) {
526     $SIG{$sig} = lc $sig;
527     is $SIG{$sig}, 'main::' . lc $sig, "Can assign to $sig";
528     is delete $SIG{$sig}, 'main::' . lc $sig, "Can delete from $sig";
529     is $SIG{$sig}, undef, "$sig is now gone";
530     is delete $SIG{$sig}, undef, "$sig remains gone";
531 }
532
533 # And now one which doesn't exist;
534 {
535     no warnings 'signal';
536     $SIG{HUNGRY} = 'mmm, pie';
537 }
538 is $SIG{HUNGRY}, 'mmm, pie', 'Can assign to HUNGRY';
539 is delete $SIG{HUNGRY}, 'mmm, pie', 'Can delete from HUNGRY';
540 is $SIG{HUNGRY}, undef, "HUNGRY is now gone";
541 is delete $SIG{HUNGRY}, undef, "HUNGRY remains gone";
542
543 # Test deleting signals that we never set
544 foreach my $sig (qw(__DIE__ _BOGUS_HOOK KILL THIRSTY)) {
545     is $SIG{$sig}, undef, "$sig is not present";
546     is delete $SIG{$sig}, undef, "delete of $sig returns undef";
547 }
548
549 {
550     $! = 9999;
551     is int $!, 9999, q{[perl #72850] Core dump in bleadperl from perl -e '$! = 9999; $a = $!;'};
552
553 }
554