This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
In t/op/filetest.t, simplify the logic for testing read-only files.
[perl5.git] / t / test.pl
1 #
2 # t/test.pl - most of Test::More functionality without the fuss, plus
3 # has mappings native_to_latin1 and latin1_to_native so that fewer tests
4 # on non ASCII-ish platforms need to be skipped
5
6
7 # NOTE:
8 #
9 # Increment ($x++) has a certain amount of cleverness for things like
10 #
11 #   $x = 'zz';
12 #   $x++; # $x eq 'aaa';
13 #
14 # stands more chance of breaking than just a simple
15 #
16 #   $x = $x + 1
17 #
18 # In this file, we use the latter "Baby Perl" approach, and increment
19 # will be worked over by t/op/inc.t
20
21 $Level = 1;
22 my $test = 1;
23 my $planned;
24 my $noplan;
25 my $Perl;       # Safer version of $^X set by which_perl()
26
27 # This defines ASCII/UTF-8 vs EBCDIC/UTF-EBCDIC
28 $::IS_ASCII  = ord 'A' ==  65;
29 $::IS_EBCDIC = ord 'A' == 193;
30
31 $TODO = 0;
32 $NO_ENDING = 0;
33 $Tests_Are_Passing = 1;
34
35 # Use this instead of print to avoid interference while testing globals.
36 sub _print {
37     local($\, $", $,) = (undef, ' ', '');
38     print STDOUT @_;
39 }
40
41 sub _print_stderr {
42     local($\, $", $,) = (undef, ' ', '');
43     print STDERR @_;
44 }
45
46 sub plan {
47     my $n;
48     if (@_ == 1) {
49         $n = shift;
50         if ($n eq 'no_plan') {
51           undef $n;
52           $noplan = 1;
53         }
54     } else {
55         my %plan = @_;
56         $n = $plan{tests};
57     }
58     _print "1..$n\n" unless $noplan;
59     $planned = $n;
60 }
61
62
63 # Set the plan at the end.  See Test::More::done_testing.
64 sub done_testing {
65     my $n = $test - 1;
66     $n = shift if @_;
67
68     _print "1..$n\n";
69     $planned = $n;
70 }
71
72
73 END {
74     my $ran = $test - 1;
75     if (!$NO_ENDING) {
76         if (defined $planned && $planned != $ran) {
77             _print_stderr
78                 "# Looks like you planned $planned tests but ran $ran.\n";
79         } elsif ($noplan) {
80             _print "1..$ran\n";
81         }
82     }
83 }
84
85 sub _diag {
86     return unless @_;
87     my @mess = _comment(@_);
88     $TODO ? _print(@mess) : _print_stderr(@mess);
89 }
90
91 # Use this instead of "print STDERR" when outputting failure diagnostic
92 # messages
93 sub diag {
94     _diag(@_);
95 }
96
97 # Use this instead of "print" when outputting informational messages
98 sub note {
99     return unless @_;
100     _print( _comment(@_) );
101 }
102
103 sub is_miniperl {
104     return !defined &DynaLoader::boot_DynaLoader;
105 }
106
107 sub _comment {
108     return map { /^#/ ? "$_\n" : "# $_\n" }
109            map { split /\n/ } @_;
110 }
111
112 sub skip_all {
113     if (@_) {
114         _print "1..0 # Skip @_\n";
115     } else {
116         _print "1..0\n";
117     }
118     exit(0);
119 }
120
121 sub skip_all_if_miniperl {
122     skip_all(@_) if is_miniperl();
123 }
124
125 sub skip_all_without_dynamic_extension {
126     my $extension = shift;
127     skip_all("no dynamic loading on miniperl, no $extension") if is_miniperl();
128     unless (eval {require Config; 1}) {
129         warn "test.pl had problems loading Config: $@";
130         return;
131     }
132     $extension =~ s!::!/!g;
133     return if ($Config::Config{extensions} =~ /\b$extension\b/);
134     skip_all("$extension was not built");
135 }
136
137 sub skip_all_without_perlio {
138     skip_all('no PerlIO') unless PerlIO::Layer->find('perlio');
139 }
140
141 sub skip_all_without_config {
142     unless (eval {require Config; 1}) {
143         warn "test.pl had problems loading Config: $@";
144         return;
145     }
146     foreach (@_) {
147         next if $Config::Config{$_};
148         my $key = $_; # Need to copy, before trying to modify.
149         $key =~ s/^use//;
150         $key =~ s/^d_//;
151         skip_all("no $key");
152     }
153 }
154
155 sub find_git_or_skip {
156     my ($found_dir, $reason);
157     if (-d '.git') {
158         $found_dir = 1;
159     } elsif (-l 'MANIFEST' && -l 'AUTHORS') {
160         my $where = readlink 'MANIFEST';
161         die "Can't readling MANIFEST: $!" unless defined $where;
162         die "Confusing symlink target for MANIFEST, '$where'"
163             unless $where =~ s!/MANIFEST\z!!;
164         if (-d "$where/.git") {
165             # Looks like we are in a symlink tree
166             chdir $where or die "Can't chdir '$where': $!";
167             note("Found source tree at $where");
168             $found_dir = 1;
169         }
170     }
171     if ($found_dir) {
172         my $version_string = `git --version`;
173         if (defined $version_string
174               && $version_string =~ /\Agit version (\d+\.\d+\.\d+)(.*)/) {
175             return if eval "v$1 ge v1.5.0";
176             # If you have earlier than 1.5.0 and it works, change this test
177             $reason = "in git checkout, but git version '$1$2' too old";
178         } else {
179             $reason = "in git checkout, but cannot run git";
180         }
181     } else {
182         $reason = 'not being run from a git checkout';
183     }
184     skip_all($reason) if $_[0] && $_[0] eq 'all';
185     skip($reason, @_);
186 }
187
188 sub _ok {
189     my ($pass, $where, $name, @mess) = @_;
190     # Do not try to microoptimize by factoring out the "not ".
191     # VMS will avenge.
192     my $out;
193     if ($name) {
194         # escape out '#' or it will interfere with '# skip' and such
195         $name =~ s/#/\\#/g;
196         $out = $pass ? "ok $test - $name" : "not ok $test - $name";
197     } else {
198         $out = $pass ? "ok $test" : "not ok $test";
199     }
200
201     if ($TODO) {
202         $out = $out . " # TODO $TODO";
203     } else {
204         $Tests_Are_Passing = 0 unless $pass;
205     }
206
207     _print "$out\n";
208
209     if ($pass) {
210         note @mess; # Ensure that the message is properly escaped.
211     }
212     else {
213         my $msg = "# Failed test $test - ";
214         $msg.= "$name " if $name;
215         $msg .= "$where\n";
216         _diag $msg;
217         _diag @mess;
218     }
219
220     $test = $test + 1; # don't use ++
221
222     return $pass;
223 }
224
225 sub _where {
226     my @caller = caller($Level);
227     return "at $caller[1] line $caller[2]";
228 }
229
230 # DON'T use this for matches. Use like() instead.
231 sub ok ($@) {
232     my ($pass, $name, @mess) = @_;
233     _ok($pass, _where(), $name, @mess);
234 }
235
236 sub _q {
237     my $x = shift;
238     return 'undef' unless defined $x;
239     my $q = $x;
240     $q =~ s/\\/\\\\/g;
241     $q =~ s/'/\\'/g;
242     return "'$q'";
243 }
244
245 sub _qq {
246     my $x = shift;
247     return defined $x ? '"' . display ($x) . '"' : 'undef';
248 };
249
250 # keys are the codes \n etc map to, values are 2 char strings such as \n
251 my %backslash_escape;
252 foreach my $x (split //, 'nrtfa\\\'"') {
253     $backslash_escape{ord eval "\"\\$x\""} = "\\$x";
254 }
255 # A way to display scalars containing control characters and Unicode.
256 # Trying to avoid setting $_, or relying on local $_ to work.
257 sub display {
258     my @result;
259     foreach my $x (@_) {
260         if (defined $x and not ref $x) {
261             my $y = '';
262             foreach my $c (unpack("U*", $x)) {
263                 if ($c > 255) {
264                     $y = $y . sprintf "\\x{%x}", $c;
265                 } elsif ($backslash_escape{$c}) {
266                     $y = $y . $backslash_escape{$c};
267                 } else {
268                     my $z = chr $c; # Maybe we can get away with a literal...
269                     if ($z =~ /[[:^print:]]/) {
270
271                         # Use octal for characters traditionally expressed as
272                         # such: the low controls
273                         if ($c <= 037) {
274                             $z = sprintf "\\%03o", $c;
275                         } else {
276                             $z = sprintf "\\x{%x}", $c;
277                         }
278                     }
279                     $y = $y . $z;
280                 }
281             }
282             $x = $y;
283         }
284         return $x unless wantarray;
285         push @result, $x;
286     }
287     return @result;
288 }
289
290 sub is ($$@) {
291     my ($got, $expected, $name, @mess) = @_;
292
293     my $pass;
294     if( !defined $got || !defined $expected ) {
295         # undef only matches undef
296         $pass = !defined $got && !defined $expected;
297     }
298     else {
299         $pass = $got eq $expected;
300     }
301
302     unless ($pass) {
303         unshift(@mess, "#      got "._qq($got)."\n",
304                        "# expected "._qq($expected)."\n");
305     }
306     _ok($pass, _where(), $name, @mess);
307 }
308
309 sub isnt ($$@) {
310     my ($got, $isnt, $name, @mess) = @_;
311
312     my $pass;
313     if( !defined $got || !defined $isnt ) {
314         # undef only matches undef
315         $pass = defined $got || defined $isnt;
316     }
317     else {
318         $pass = $got ne $isnt;
319     }
320
321     unless( $pass ) {
322         unshift(@mess, "# it should not be "._qq($got)."\n",
323                        "# but it is.\n");
324     }
325     _ok($pass, _where(), $name, @mess);
326 }
327
328 sub cmp_ok ($$$@) {
329     my($got, $type, $expected, $name, @mess) = @_;
330
331     my $pass;
332     {
333         local $^W = 0;
334         local($@,$!);   # don't interfere with $@
335                         # eval() sometimes resets $!
336         $pass = eval "\$got $type \$expected";
337     }
338     unless ($pass) {
339         # It seems Irix long doubles can have 2147483648 and 2147483648
340         # that stringify to the same thing but are actually numerically
341         # different. Display the numbers if $type isn't a string operator,
342         # and the numbers are stringwise the same.
343         # (all string operators have alphabetic names, so tr/a-z// is true)
344         # This will also show numbers for some unneeded cases, but will
345         # definitely be helpful for things such as == and <= that fail
346         if ($got eq $expected and $type !~ tr/a-z//) {
347             unshift @mess, "# $got - $expected = " . ($got - $expected) . "\n";
348         }
349         unshift(@mess, "#      got "._qq($got)."\n",
350                        "# expected $type "._qq($expected)."\n");
351     }
352     _ok($pass, _where(), $name, @mess);
353 }
354
355 # Check that $got is within $range of $expected
356 # if $range is 0, then check it's exact
357 # else if $expected is 0, then $range is an absolute value
358 # otherwise $range is a fractional error.
359 # Here $range must be numeric, >= 0
360 # Non numeric ranges might be a useful future extension. (eg %)
361 sub within ($$$@) {
362     my ($got, $expected, $range, $name, @mess) = @_;
363     my $pass;
364     if (!defined $got or !defined $expected or !defined $range) {
365         # This is a fail, but doesn't need extra diagnostics
366     } elsif ($got !~ tr/0-9// or $expected !~ tr/0-9// or $range !~ tr/0-9//) {
367         # This is a fail
368         unshift @mess, "# got, expected and range must be numeric\n";
369     } elsif ($range < 0) {
370         # This is also a fail
371         unshift @mess, "# range must not be negative\n";
372     } elsif ($range == 0) {
373         # Within 0 is ==
374         $pass = $got == $expected;
375     } elsif ($expected == 0) {
376         # If expected is 0, treat range as absolute
377         $pass = ($got <= $range) && ($got >= - $range);
378     } else {
379         my $diff = $got - $expected;
380         $pass = abs ($diff / $expected) < $range;
381     }
382     unless ($pass) {
383         if ($got eq $expected) {
384             unshift @mess, "# $got - $expected = " . ($got - $expected) . "\n";
385         }
386         unshift@mess, "#      got "._qq($got)."\n",
387                       "# expected "._qq($expected)." (within "._qq($range).")\n";
388     }
389     _ok($pass, _where(), $name, @mess);
390 }
391
392 # Note: this isn't quite as fancy as Test::More::like().
393
394 sub like   ($$@) { like_yn (0,@_) }; # 0 for -
395 sub unlike ($$@) { like_yn (1,@_) }; # 1 for un-
396
397 sub like_yn ($$$@) {
398     my ($flip, undef, $expected, $name, @mess) = @_;
399     my $pass;
400     $pass = $_[1] =~ /$expected/ if !$flip;
401     $pass = $_[1] !~ /$expected/ if $flip;
402     unless ($pass) {
403         unshift(@mess, "#      got '$_[1]'\n",
404                 $flip
405                 ? "# expected !~ /$expected/\n" : "# expected /$expected/\n");
406     }
407     local $Level = $Level + 1;
408     _ok($pass, _where(), $name, @mess);
409 }
410
411 sub pass {
412     _ok(1, '', @_);
413 }
414
415 sub fail {
416     _ok(0, _where(), @_);
417 }
418
419 sub curr_test {
420     $test = shift if @_;
421     return $test;
422 }
423
424 sub next_test {
425   my $retval = $test;
426   $test = $test + 1; # don't use ++
427   $retval;
428 }
429
430 # Note: can't pass multipart messages since we try to
431 # be compatible with Test::More::skip().
432 sub skip {
433     my $why = shift;
434     my $n    = @_ ? shift : 1;
435     for (1..$n) {
436         _print "ok $test # skip $why\n";
437         $test = $test + 1;
438     }
439     local $^W = 0;
440     last SKIP;
441 }
442
443 sub skip_if_miniperl {
444     skip(@_) if is_miniperl();
445 }
446
447 sub todo_skip {
448     my $why = shift;
449     my $n   = @_ ? shift : 1;
450
451     for (1..$n) {
452         _print "not ok $test # TODO & SKIP $why\n";
453         $test = $test + 1;
454     }
455     local $^W = 0;
456     last TODO;
457 }
458
459 sub eq_array {
460     my ($ra, $rb) = @_;
461     return 0 unless $#$ra == $#$rb;
462     for my $i (0..$#$ra) {
463         next     if !defined $ra->[$i] && !defined $rb->[$i];
464         return 0 if !defined $ra->[$i];
465         return 0 if !defined $rb->[$i];
466         return 0 unless $ra->[$i] eq $rb->[$i];
467     }
468     return 1;
469 }
470
471 sub eq_hash {
472   my ($orig, $suspect) = @_;
473   my $fail;
474   while (my ($key, $value) = each %$suspect) {
475     # Force a hash recompute if this perl's internals can cache the hash key.
476     $key = "" . $key;
477     if (exists $orig->{$key}) {
478       if ($orig->{$key} ne $value) {
479         _print "# key ", _qq($key), " was ", _qq($orig->{$key}),
480                      " now ", _qq($value), "\n";
481         $fail = 1;
482       }
483     } else {
484       _print "# key ", _qq($key), " is ", _qq($value),
485                    ", not in original.\n";
486       $fail = 1;
487     }
488   }
489   foreach (keys %$orig) {
490     # Force a hash recompute if this perl's internals can cache the hash key.
491     $_ = "" . $_;
492     next if (exists $suspect->{$_});
493     _print "# key ", _qq($_), " was ", _qq($orig->{$_}), " now missing.\n";
494     $fail = 1;
495   }
496   !$fail;
497 }
498
499 # We only provide a subset of the Test::More functionality.
500 sub require_ok ($) {
501     my ($require) = @_;
502     if ($require =~ tr/[A-Za-z0-9:.]//c) {
503         fail("Invalid character in \"$require\", passed to require_ok");
504     } else {
505         eval <<REQUIRE_OK;
506 require $require;
507 REQUIRE_OK
508         is($@, '', _where(), "require $require");
509     }
510 }
511
512 sub use_ok ($) {
513     my ($use) = @_;
514     if ($use =~ tr/[A-Za-z0-9:.]//c) {
515         fail("Invalid character in \"$use\", passed to use");
516     } else {
517         eval <<USE_OK;
518 use $use;
519 USE_OK
520         is($@, '', _where(), "use $use");
521     }
522 }
523
524 # runperl - Runs a separate perl interpreter.
525 # Arguments :
526 #   switches => [ command-line switches ]
527 #   nolib    => 1 # don't use -I../lib (included by default)
528 #   non_portable => Don't warn if a one liner contains quotes
529 #   prog     => one-liner (avoid quotes)
530 #   progs    => [ multi-liner (avoid quotes) ]
531 #   progfile => perl script
532 #   stdin    => string to feed the stdin
533 #   stderr   => redirect stderr to stdout
534 #   args     => [ command-line arguments to the perl program ]
535 #   verbose  => print the command line
536
537 my $is_mswin    = $^O eq 'MSWin32';
538 my $is_netware  = $^O eq 'NetWare';
539 my $is_vms      = $^O eq 'VMS';
540 my $is_cygwin   = $^O eq 'cygwin';
541
542 sub _quote_args {
543     my ($runperl, $args) = @_;
544
545     foreach (@$args) {
546         # In VMS protect with doublequotes because otherwise
547         # DCL will lowercase -- unless already doublequoted.
548        $_ = q(").$_.q(") if $is_vms && !/^\"/ && length($_) > 0;
549        $runperl = $runperl . ' ' . $_;
550     }
551     return $runperl;
552 }
553
554 sub _create_runperl { # Create the string to qx in runperl().
555     my %args = @_;
556     my $runperl = which_perl();
557     if ($runperl =~ m/\s/) {
558         $runperl = qq{"$runperl"};
559     }
560     #- this allows, for example, to set PERL_RUNPERL_DEBUG=/usr/bin/valgrind
561     if ($ENV{PERL_RUNPERL_DEBUG}) {
562         $runperl = "$ENV{PERL_RUNPERL_DEBUG} $runperl";
563     }
564     unless ($args{nolib}) {
565         $runperl = $runperl . ' "-I../lib"'; # doublequotes because of VMS
566     }
567     if ($args{switches}) {
568         local $Level = 2;
569         die "test.pl:runperl(): 'switches' must be an ARRAYREF " . _where()
570             unless ref $args{switches} eq "ARRAY";
571         $runperl = _quote_args($runperl, $args{switches});
572     }
573     if (defined $args{prog}) {
574         die "test.pl:runperl(): both 'prog' and 'progs' cannot be used " . _where()
575             if defined $args{progs};
576         $args{progs} = [$args{prog}]
577     }
578     if (defined $args{progs}) {
579         die "test.pl:runperl(): 'progs' must be an ARRAYREF " . _where()
580             unless ref $args{progs} eq "ARRAY";
581         foreach my $prog (@{$args{progs}}) {
582             if ($prog =~ tr/'"// && !$args{non_portable}) {
583                 warn "quotes in prog >>$prog<< are not portable";
584             }
585             if ($is_mswin || $is_netware || $is_vms) {
586                 $runperl = $runperl . qq ( -e "$prog" );
587             }
588             else {
589                 $runperl = $runperl . qq ( -e '$prog' );
590             }
591         }
592     } elsif (defined $args{progfile}) {
593         $runperl = $runperl . qq( "$args{progfile}");
594     } else {
595         # You probably didn't want to be sucking in from the upstream stdin
596         die "test.pl:runperl(): none of prog, progs, progfile, args, "
597             . " switches or stdin specified"
598             unless defined $args{args} or defined $args{switches}
599                 or defined $args{stdin};
600     }
601     if (defined $args{stdin}) {
602         # so we don't try to put literal newlines and crs onto the
603         # command line.
604         $args{stdin} =~ s/\n/\\n/g;
605         $args{stdin} =~ s/\r/\\r/g;
606
607         if ($is_mswin || $is_netware || $is_vms) {
608             $runperl = qq{$Perl -e "print qq(} .
609                 $args{stdin} . q{)" | } . $runperl;
610         }
611         else {
612             $runperl = qq{$Perl -e 'print qq(} .
613                 $args{stdin} . q{)' | } . $runperl;
614         }
615     }
616     if (defined $args{args}) {
617         $runperl = _quote_args($runperl, $args{args});
618     }
619     $runperl = $runperl . ' 2>&1' if $args{stderr};
620     if ($args{verbose}) {
621         my $runperldisplay = $runperl;
622         $runperldisplay =~ s/\n/\n\#/g;
623         _print_stderr "# $runperldisplay\n";
624     }
625     return $runperl;
626 }
627
628 sub runperl {
629     die "test.pl:runperl() does not take a hashref"
630         if ref $_[0] and ref $_[0] eq 'HASH';
631     my $runperl = &_create_runperl;
632     my $result;
633
634     my $tainted = ${^TAINT};
635     my %args = @_;
636     exists $args{switches} && grep m/^-T$/, @{$args{switches}} and $tainted = $tainted + 1;
637
638     if ($tainted) {
639         # We will assume that if you're running under -T, you really mean to
640         # run a fresh perl, so we'll brute force launder everything for you
641         my $sep;
642
643         if (! eval {require Config; 1}) {
644             warn "test.pl had problems loading Config: $@";
645             $sep = ':';
646         } else {
647             $sep = $Config::Config{path_sep};
648         }
649
650         my @keys = grep {exists $ENV{$_}} qw(CDPATH IFS ENV BASH_ENV);
651         local @ENV{@keys} = ();
652         # Untaint, plus take out . and empty string:
653         local $ENV{'DCL$PATH'} = $1 if $is_vms && exists($ENV{'DCL$PATH'}) && ($ENV{'DCL$PATH'} =~ /(.*)/s);
654         $ENV{PATH} =~ /(.*)/s;
655         local $ENV{PATH} =
656             join $sep, grep { $_ ne "" and $_ ne "." and -d $_ and
657                 ($is_mswin or $is_vms or !(stat && (stat _)[2]&0022)) }
658                     split quotemeta ($sep), $1;
659         if ($is_cygwin) {   # Must have /bin under Cygwin
660             if (length $ENV{PATH}) {
661                 $ENV{PATH} = $ENV{PATH} . $sep;
662             }
663             $ENV{PATH} = $ENV{PATH} . '/bin';
664         }
665         $runperl =~ /(.*)/s;
666         $runperl = $1;
667
668         $result = `$runperl`;
669     } else {
670         $result = `$runperl`;
671     }
672     $result =~ s/\n\n/\n/ if $is_vms; # XXX pipes sometimes double these
673     return $result;
674 }
675
676 # Nice alias
677 *run_perl = *run_perl = \&runperl; # shut up "used only once" warning
678
679 sub DIE {
680     _print_stderr "# @_\n";
681     exit 1;
682 }
683
684 # A somewhat safer version of the sometimes wrong $^X.
685 sub which_perl {
686     unless (defined $Perl) {
687         $Perl = $^X;
688
689         # VMS should have 'perl' aliased properly
690         return $Perl if $is_vms;
691
692         my $exe;
693         if (! eval {require Config; 1}) {
694             warn "test.pl had problems loading Config: $@";
695             $exe = '';
696         } else {
697             $exe = $Config::Config{_exe};
698         }
699        $exe = '' unless defined $exe;
700
701         # This doesn't absolutize the path: beware of future chdirs().
702         # We could do File::Spec->abs2rel() but that does getcwd()s,
703         # which is a bit heavyweight to do here.
704
705         if ($Perl =~ /^perl\Q$exe\E$/i) {
706             my $perl = "perl$exe";
707             if (! eval {require File::Spec; 1}) {
708                 warn "test.pl had problems loading File::Spec: $@";
709                 $Perl = "./$perl";
710             } else {
711                 $Perl = File::Spec->catfile(File::Spec->curdir(), $perl);
712             }
713         }
714
715         # Build up the name of the executable file from the name of
716         # the command.
717
718         if ($Perl !~ /\Q$exe\E$/i) {
719             $Perl = $Perl . $exe;
720         }
721
722         warn "which_perl: cannot find $Perl from $^X" unless -f $Perl;
723
724         # For subcommands to use.
725         $ENV{PERLEXE} = $Perl;
726     }
727     return $Perl;
728 }
729
730 sub unlink_all {
731     my $count = 0;
732     foreach my $file (@_) {
733         1 while unlink $file;
734         if( -f $file ){
735             _print_stderr "# Couldn't unlink '$file': $!\n";
736         }else{
737             ++$count;
738         }
739     }
740     $count;
741 }
742
743 my %tmpfiles;
744 END { unlink_all keys %tmpfiles }
745
746 # A regexp that matches the tempfile names
747 $::tempfile_regexp = 'tmp\d+[A-Z][A-Z]?';
748
749 # Avoid ++, avoid ranges, avoid split //
750 my @letters = qw(A B C D E F G H I J K L M N O P Q R S T U V W X Y Z);
751 sub tempfile {
752     my $count = 0;
753     do {
754         my $temp = $count;
755         my $try = "tmp$$";
756         do {
757             $try = $try . $letters[$temp % 26];
758             $temp = int ($temp / 26);
759         } while $temp;
760         # Need to note all the file names we allocated, as a second request may
761         # come before the first is created.
762         if (!-e $try && !$tmpfiles{$try}) {
763             # We have a winner
764             $tmpfiles{$try} = 1;
765             return $try;
766         }
767         $count = $count + 1;
768     } while $count < 26 * 26;
769     die "Can't find temporary file name starting 'tmp$$'";
770 }
771
772 # This is the temporary file for _fresh_perl
773 my $tmpfile = tempfile();
774
775 sub _fresh_perl {
776     my($prog, $action, $expect, $runperl_args, $name) = @_;
777
778     # Given the choice of the mis-parsable {}
779     # (we want an anon hash, but a borked lexer might think that it's a block)
780     # or relying on taking a reference to a lexical
781     # (\ might be mis-parsed, and the reference counting on the pad may go
782     #  awry)
783     # it feels like the least-worse thing is to assume that auto-vivification
784     # works. At least, this is only going to be a run-time failure, so won't
785     # affect tests using this file but not this function.
786     $runperl_args->{progfile} = $tmpfile;
787     $runperl_args->{stderr} = 1;
788
789     open TEST, ">$tmpfile" or die "Cannot open $tmpfile: $!";
790
791     # VMS adjustments
792     if( $is_vms ) {
793         $prog =~ s#/dev/null#NL:#;
794
795         # VMS file locking
796         $prog =~ s{if \(-e _ and -f _ and -r _\)}
797                   {if (-e _ and -f _)}
798     }
799
800     print TEST $prog;
801     close TEST or die "Cannot close $tmpfile: $!";
802
803     my $results = runperl(%$runperl_args);
804     my $status = $?;
805
806     # Clean up the results into something a bit more predictable.
807     $results  =~ s/\n+$//;
808     $results =~ s/at\s+$::tempfile_regexp\s+line/at - line/g;
809     $results =~ s/of\s+$::tempfile_regexp\s+aborted/of - aborted/g;
810
811     # bison says 'parse error' instead of 'syntax error',
812     # various yaccs may or may not capitalize 'syntax'.
813     $results =~ s/^(syntax|parse) error/syntax error/mig;
814
815     if ($is_vms) {
816         # some tests will trigger VMS messages that won't be expected
817         $results =~ s/\n?%[A-Z]+-[SIWEF]-[A-Z]+,.*//;
818
819         # pipes double these sometimes
820         $results =~ s/\n\n/\n/g;
821     }
822
823     # Use the first line of the program as a name if none was given
824     unless( $name ) {
825         ($first_line, $name) = $prog =~ /^((.{1,50}).*)/;
826         $name = $name . '...' if length $first_line > length $name;
827     }
828
829     # Historically this was implemented using a closure, but then that means
830     # that the tests for closures avoid using this code. Given that there
831     # are exactly two callers, doing exactly two things, the simpler approach
832     # feels like a better trade off.
833     my $pass;
834     if ($action eq 'eq') {
835         $pass = is($results, $expect, $name);
836     } elsif ($action eq '=~') {
837         $pass = like($results, $expect, $name);
838     } else {
839         die "_fresh_perl can't process action '$action'";
840     }
841         
842     unless ($pass) {
843         _diag "# PROG: \n$prog\n";
844         _diag "# STATUS: $status\n";
845     }
846
847     return $pass;
848 }
849
850 #
851 # fresh_perl_is
852 #
853 # Combination of run_perl() and is().
854 #
855
856 sub fresh_perl_is {
857     my($prog, $expected, $runperl_args, $name) = @_;
858
859     # _fresh_perl() is going to clip the trailing newlines off the result.
860     # This will make it so the test author doesn't have to know that.
861     $expected =~ s/\n+$//;
862
863     local $Level = 2;
864     _fresh_perl($prog, 'eq', $expected, $runperl_args, $name);
865 }
866
867 #
868 # fresh_perl_like
869 #
870 # Combination of run_perl() and like().
871 #
872
873 sub fresh_perl_like {
874     my($prog, $expected, $runperl_args, $name) = @_;
875     local $Level = 2;
876     _fresh_perl($prog, '=~', $expected, $runperl_args, $name);
877 }
878
879 # Many tests use the same format in __DATA__ or external files to specify a
880 # sequence of (fresh) tests to run, extra files they may temporarily need, and
881 # what the expected output is. So have excatly one copy of the code to run that
882 #
883 # Each program is source code to run followed by an "EXPECT" line, followed
884 # by the expected output.
885 #
886 # The code to run may contain (note the '# ' on each):
887 #   # TODO reason for todo
888 #   # SKIP reason for skip
889 #   # SKIP ?code to test if this should be skipped
890 #   # NAME name of the test (as with ok($ok, $name))
891 #
892 # The expected output may contain:
893 #   OPTION list of options
894 #   OPTIONS list of options
895 #   PREFIX
896 #     indicates that the supplied output is only a prefix to the
897 #     expected output
898 #
899 # The possible options for OPTION may be:
900 #   regex - the expected output is a regular expression
901 #   random - all lines match but in any order
902 #   fatal - the code will fail fatally (croak, die)
903 #
904 # If the actual output contains a line "SKIPPED" the test will be
905 # skipped.
906 #
907 # If the global variable $FATAL is true then OPTION fatal is the
908 # default.
909
910 sub run_multiple_progs {
911     my $up = shift;
912     my @prgs;
913     if ($up) {
914         # The tests in lib run in a temporary subdirectory of t, and always
915         # pass in a list of "programs" to run
916         @prgs = @_;
917     } else {
918         # The tests below t run in t and pass in a file handle.
919         my $fh = shift;
920         local $/;
921         @prgs = split "\n########\n", <$fh>;
922     }
923
924     my $tmpfile = tempfile();
925
926     for (@prgs){
927         unless (/\n/) {
928             print "# From $_\n";
929             next;
930         }
931         my $switch = "";
932         my @temps ;
933         my @temp_path;
934         if (s/^(\s*-\w+)//) {
935             $switch = $1;
936         }
937         my ($prog, $expected) = split(/\nEXPECT(?:\n|$)/, $_, 2);
938
939         my %reason;
940         foreach my $what (qw(skip todo)) {
941             $prog =~ s/^#\s*\U$what\E\s*(.*)\n//m and $reason{$what} = $1;
942             # If the SKIP reason starts ? then it's taken as a code snippet to
943             # evaluate. This provides the flexibility to have conditional SKIPs
944             if ($reason{$what} && $reason{$what} =~ s/^\?//) {
945                 my $temp = eval $reason{$what};
946                 if ($@) {
947                     die "# In \U$what\E code reason:\n# $reason{$what}\n$@";
948                 }
949                 $reason{$what} = $temp;
950             }
951         }
952         my $name = '';
953         if ($prog =~ s/^#\s*NAME\s+(.+)\n//m) {
954             $name = $1;
955         }
956
957         if ($prog =~ /--FILE--/) {
958             my @files = split(/\n--FILE--\s*([^\s\n]*)\s*\n/, $prog) ;
959             shift @files ;
960             die "Internal error: test $_ didn't split into pairs, got " .
961                 scalar(@files) . "[" . join("%%%%", @files) ."]\n"
962                     if @files % 2;
963             while (@files > 2) {
964                 my $filename = shift @files;
965                 my $code = shift @files;
966                 push @temps, $filename;
967                 if ($filename =~ m#(.*)/# && $filename !~ m#^\.\./#) {
968                     require File::Path;
969                     File::Path::mkpath($1);
970                     push(@temp_path, $1);
971                 }
972                 open my $fh, '>', $filename or die "Cannot open $filename: $!\n";
973                 print $fh $code;
974                 close $fh or die "Cannot close $filename: $!\n";
975             }
976             shift @files;
977             $prog = shift @files;
978         }
979
980         open my $fh, '>', $tmpfile or die "Cannot open >$tmpfile: $!";
981         print $fh q{
982         BEGIN {
983             open STDERR, '>&', STDOUT
984               or die "Can't dup STDOUT->STDERR: $!;";
985         }
986         };
987         print $fh "\n#line 1\n";  # So the line numbers don't get messed up.
988         print $fh $prog,"\n";
989         close $fh or die "Cannot close $tmpfile: $!";
990         my $results = runperl( stderr => 1, progfile => $tmpfile, $up
991                                ? (switches => ["-I$up/lib", $switch], nolib => 1)
992                                : (switches => [$switch])
993                                 );
994         my $status = $?;
995         $results =~ s/\n+$//;
996         # allow expected output to be written as if $prog is on STDIN
997         $results =~ s/$::tempfile_regexp/-/g;
998         if ($^O eq 'VMS') {
999             # some tests will trigger VMS messages that won't be expected
1000             $results =~ s/\n?%[A-Z]+-[SIWEF]-[A-Z]+,.*//;
1001
1002             # pipes double these sometimes
1003             $results =~ s/\n\n/\n/g;
1004         }
1005         # bison says 'parse error' instead of 'syntax error',
1006         # various yaccs may or may not capitalize 'syntax'.
1007         $results =~ s/^(syntax|parse) error/syntax error/mig;
1008         # allow all tests to run when there are leaks
1009         $results =~ s/Scalars leaked: \d+\n//g;
1010
1011         $expected =~ s/\n+$//;
1012         my $prefix = ($results =~ s#^PREFIX(\n|$)##) ;
1013         # any special options? (OPTIONS foo bar zap)
1014         my $option_regex = 0;
1015         my $option_random = 0;
1016         my $fatal = $FATAL;
1017         if ($expected =~ s/^OPTIONS? (.+)\n//) {
1018             foreach my $option (split(' ', $1)) {
1019                 if ($option eq 'regex') { # allow regular expressions
1020                     $option_regex = 1;
1021                 }
1022                 elsif ($option eq 'random') { # all lines match, but in any order
1023                     $option_random = 1;
1024                 }
1025                 elsif ($option eq 'fatal') { # perl should fail
1026                     $fatal = 1;
1027                 }
1028                 else {
1029                     die "$0: Unknown OPTION '$option'\n";
1030                 }
1031             }
1032         }
1033         die "$0: can't have OPTION regex and random\n"
1034             if $option_regex + $option_random > 1;
1035         my $ok = 0;
1036         if ($results =~ s/^SKIPPED\n//) {
1037             print "$results\n" ;
1038             $ok = 1;
1039         }
1040         else {
1041             if ($option_random) {
1042                 my @got = sort split "\n", $results;
1043                 my @expected = sort split "\n", $expected;
1044
1045                 $ok = "@got" eq "@expected";
1046             }
1047             elsif ($option_regex) {
1048                 $ok = $results =~ /^$expected/;
1049             }
1050             elsif ($prefix) {
1051                 $ok = $results =~ /^\Q$expected/;
1052             }
1053             else {
1054                 $ok = $results eq $expected;
1055             }
1056
1057             if ($ok && $fatal && !($status >> 8)) {
1058                 $ok = 0;
1059             }
1060         }
1061
1062         local $::TODO = $reason{todo};
1063
1064         unless ($ok) {
1065             my $err_line = "PROG: $switch\n$prog\n" .
1066                            "EXPECTED:\n$expected\n";
1067             $err_line   .= "EXIT STATUS: != 0\n" if $fatal;
1068             $err_line   .= "GOT:\n$results\n";
1069             $err_line   .= "EXIT STATUS: " . ($status >> 8) . "\n" if $fatal;
1070             if ($::TODO) {
1071                 $err_line =~ s/^/# /mg;
1072                 print $err_line;  # Harness can't filter it out from STDERR.
1073             }
1074             else {
1075                 print STDERR $err_line;
1076             }
1077         }
1078
1079         ok($ok, $name);
1080
1081         foreach (@temps) {
1082             unlink $_ if $_;
1083         }
1084         foreach (@temp_path) {
1085             File::Path::rmtree $_ if -d $_;
1086         }
1087     }
1088 }
1089
1090 sub can_ok ($@) {
1091     my($proto, @methods) = @_;
1092     my $class = ref $proto || $proto;
1093
1094     unless( @methods ) {
1095         return _ok( 0, _where(), "$class->can(...)" );
1096     }
1097
1098     my @nok = ();
1099     foreach my $method (@methods) {
1100         local($!, $@);  # don't interfere with caller's $@
1101                         # eval sometimes resets $!
1102         eval { $proto->can($method) } || push @nok, $method;
1103     }
1104
1105     my $name;
1106     $name = @methods == 1 ? "$class->can('$methods[0]')"
1107                           : "$class->can(...)";
1108
1109     _ok( !@nok, _where(), $name );
1110 }
1111
1112
1113 # Call $class->new( @$args ); and run the result through object_ok.
1114 # See Test::More::new_ok
1115 sub new_ok {
1116     my($class, $args, $obj_name) = @_;
1117     $args ||= [];
1118     $object_name = "The object" unless defined $obj_name;
1119
1120     local $Level = $Level + 1;
1121
1122     my $obj;
1123     my $ok = eval { $obj = $class->new(@$args); 1 };
1124     my $error = $@;
1125
1126     if($ok) {
1127         object_ok($obj, $class, $object_name);
1128     }
1129     else {
1130         ok( 0, "new() died" );
1131         diag("Error was:  $@");
1132     }
1133
1134     return $obj;
1135
1136 }
1137
1138
1139 sub isa_ok ($$;$) {
1140     my($object, $class, $obj_name) = @_;
1141
1142     my $diag;
1143     $obj_name = 'The object' unless defined $obj_name;
1144     my $name = "$obj_name isa $class";
1145     if( !defined $object ) {
1146         $diag = "$obj_name isn't defined";
1147     }
1148     else {
1149         my $whatami = ref $object ? 'object' : 'class';
1150
1151         # We can't use UNIVERSAL::isa because we want to honor isa() overrides
1152         local($@, $!);  # eval sometimes resets $!
1153         my $rslt = eval { $object->isa($class) };
1154         my $error = $@;  # in case something else blows away $@
1155
1156         if( $error ) {
1157             if( $error =~ /^Can't call method "isa" on unblessed reference/ ) {
1158                 # It's an unblessed reference
1159                 $obj_name = 'The reference' unless defined $obj_name;
1160                 if( !UNIVERSAL::isa($object, $class) ) {
1161                     my $ref = ref $object;
1162                     $diag = "$obj_name isn't a '$class' it's a '$ref'";
1163                 }
1164             }
1165             elsif( $error =~ /Can't call method "isa" without a package/ ) {
1166                 # It's something that can't even be a class
1167                 $obj_name = 'The thing' unless defined $obj_name;
1168                 $diag = "$obj_name isn't a class or reference";
1169             }
1170             else {
1171                 die <<WHOA;
1172 WHOA! I tried to call ->isa on your object and got some weird error.
1173 This should never happen.  Please contact the author immediately.
1174 Here's the error.
1175 $@
1176 WHOA
1177             }
1178         }
1179         elsif( !$rslt ) {
1180             $obj_name = "The $whatami" unless defined $obj_name;
1181             my $ref = ref $object;
1182             $diag = "$obj_name isn't a '$class' it's a '$ref'";
1183         }
1184     }
1185
1186     _ok( !$diag, _where(), $name );
1187 }
1188
1189
1190 sub class_ok {
1191     my($class, $isa, $class_name) = @_;
1192
1193     # Written so as to count as one test
1194     local $Level = $Level + 1;
1195     if( ref $class ) {
1196         ok( 0, "$class is a refrence, not a class name" );
1197     }
1198     else {
1199         isa_ok($class, $isa, $class_name);
1200     }
1201 }
1202
1203
1204 sub object_ok {
1205     my($obj, $isa, $obj_name) = @_;
1206
1207     local $Level = $Level + 1;
1208     if( !ref $obj ) {
1209         ok( 0, "$obj is not a reference" );
1210     }
1211     else {
1212         isa_ok($obj, $isa, $obj_name);
1213     }
1214 }
1215
1216
1217 # Purposefully avoiding a closure.
1218 sub __capture {
1219     push @::__capture, join "", @_;
1220 }
1221     
1222 sub capture_warnings {
1223     my $code = shift;
1224
1225     local @::__capture;
1226     local $SIG {__WARN__} = \&__capture;
1227     &$code;
1228     return @::__capture;
1229 }
1230
1231 # This will generate a variable number of tests.
1232 # Use done_testing() instead of a fixed plan.
1233 sub warnings_like {
1234     my ($code, $expect, $name) = @_;
1235     local $Level = $Level + 1;
1236
1237     my @w = capture_warnings($code);
1238
1239     cmp_ok(scalar @w, '==', scalar @$expect, $name);
1240     foreach my $e (@$expect) {
1241         if (ref $e) {
1242             like(shift @w, $e, $name);
1243         } else {
1244             is(shift @w, $e, $name);
1245         }
1246     }
1247     if (@w) {
1248         diag("Saw these additional warnings:");
1249         diag($_) foreach @w;
1250     }
1251 }
1252
1253 sub _fail_excess_warnings {
1254     my($expect, $got, $name) = @_;
1255     local $Level = $Level + 1;
1256     # This will fail, and produce diagnostics
1257     is($expect, scalar @$got, $name);
1258     diag("Saw these warnings:");
1259     diag($_) foreach @$got;
1260 }
1261
1262 sub warning_is {
1263     my ($code, $expect, $name) = @_;
1264     die sprintf "Expect must be a string or undef, not a %s reference", ref $expect
1265         if ref $expect;
1266     local $Level = $Level + 1;
1267     my @w = capture_warnings($code);
1268     if (@w > 1) {
1269         _fail_excess_warnings(0 + defined $expect, \@w, $name);
1270     } else {
1271         is($w[0], $expect, $name);
1272     }
1273 }
1274
1275 sub warning_like {
1276     my ($code, $expect, $name) = @_;
1277     die sprintf "Expect must be a regexp object"
1278         unless ref $expect eq 'Regexp';
1279     local $Level = $Level + 1;
1280     my @w = capture_warnings($code);
1281     if (@w > 1) {
1282         _fail_excess_warnings(0 + defined $expect, \@w, $name);
1283     } else {
1284         like($w[0], $expect, $name);
1285     }
1286 }
1287
1288 # Set a watchdog to timeout the entire test file
1289 # NOTE:  If the test file uses 'threads', then call the watchdog() function
1290 #        _AFTER_ the 'threads' module is loaded.
1291 sub watchdog ($;$)
1292 {
1293     my $timeout = shift;
1294     my $method  = shift || "";
1295     my $timeout_msg = 'Test process timed out - terminating';
1296
1297     # Valgrind slows perl way down so give it more time before dying.
1298     $timeout *= 10 if $ENV{PERL_VALGRIND};
1299
1300     my $pid_to_kill = $$;   # PID for this process
1301
1302     if ($method eq "alarm") {
1303         goto WATCHDOG_VIA_ALARM;
1304     }
1305
1306     # shut up use only once warning
1307     my $threads_on = $threads::threads && $threads::threads;
1308
1309     # Don't use a watchdog process if 'threads' is loaded -
1310     #   use a watchdog thread instead
1311     if (!$threads_on || $method eq "process") {
1312
1313         # On Windows and VMS, try launching a watchdog process
1314         #   using system(1, ...) (see perlport.pod)
1315         if ($is_mswin || $is_vms) {
1316             # On Windows, try to get the 'real' PID
1317             if ($is_mswin) {
1318                 eval { require Win32; };
1319                 if (defined(&Win32::GetCurrentProcessId)) {
1320                     $pid_to_kill = Win32::GetCurrentProcessId();
1321                 }
1322             }
1323
1324             # If we still have a fake PID, we can't use this method at all
1325             return if ($pid_to_kill <= 0);
1326
1327             # Launch watchdog process
1328             my $watchdog;
1329             eval {
1330                 local $SIG{'__WARN__'} = sub {
1331                     _diag("Watchdog warning: $_[0]");
1332                 };
1333                 my $sig = $is_vms ? 'TERM' : 'KILL';
1334                 my $cmd = _create_runperl( prog =>  "sleep($timeout);" .
1335                                                     "warn qq/# $timeout_msg" . '\n/;' .
1336                                                     "kill($sig, $pid_to_kill);");
1337                 $watchdog = system(1, $cmd);
1338             };
1339             if ($@ || ($watchdog <= 0)) {
1340                 _diag('Failed to start watchdog');
1341                 _diag($@) if $@;
1342                 undef($watchdog);
1343                 return;
1344             }
1345
1346             # Add END block to parent to terminate and
1347             #   clean up watchdog process
1348             eval "END { local \$! = 0; local \$? = 0;
1349                         wait() if kill('KILL', $watchdog); };";
1350             return;
1351         }
1352
1353         # Try using fork() to generate a watchdog process
1354         my $watchdog;
1355         eval { $watchdog = fork() };
1356         if (defined($watchdog)) {
1357             if ($watchdog) {   # Parent process
1358                 # Add END block to parent to terminate and
1359                 #   clean up watchdog process
1360                 eval "END { local \$! = 0; local \$? = 0;
1361                             wait() if kill('KILL', $watchdog); };";
1362                 return;
1363             }
1364
1365             ### Watchdog process code
1366
1367             # Load POSIX if available
1368             eval { require POSIX; };
1369
1370             # Execute the timeout
1371             sleep($timeout - 2) if ($timeout > 2);   # Workaround for perlbug #49073
1372             sleep(2);
1373
1374             # Kill test process if still running
1375             if (kill(0, $pid_to_kill)) {
1376                 _diag($timeout_msg);
1377                 kill('KILL', $pid_to_kill);
1378                 if ($is_cygwin) {
1379                     # sometimes the above isn't enough on cygwin
1380                     sleep 1; # wait a little, it might have worked after all
1381                     system("/bin/kill -f $pid_to_kill");
1382                 }
1383             }
1384
1385             # Don't execute END block (added at beginning of this file)
1386             $NO_ENDING = 1;
1387
1388             # Terminate ourself (i.e., the watchdog)
1389             POSIX::_exit(1) if (defined(&POSIX::_exit));
1390             exit(1);
1391         }
1392
1393         # fork() failed - fall through and try using a thread
1394     }
1395
1396     # Use a watchdog thread because either 'threads' is loaded,
1397     #   or fork() failed
1398     if (eval {require threads; 1}) {
1399         'threads'->create(sub {
1400                 # Load POSIX if available
1401                 eval { require POSIX; };
1402
1403                 # Execute the timeout
1404                 my $time_left = $timeout;
1405                 do {
1406                     $time_left = $time_left - sleep($time_left);
1407                 } while ($time_left > 0);
1408
1409                 # Kill the parent (and ourself)
1410                 select(STDERR); $| = 1;
1411                 _diag($timeout_msg);
1412                 POSIX::_exit(1) if (defined(&POSIX::_exit));
1413                 my $sig = $is_vms ? 'TERM' : 'KILL';
1414                 kill($sig, $pid_to_kill);
1415             })->detach();
1416         return;
1417     }
1418
1419     # If everything above fails, then just use an alarm timeout
1420 WATCHDOG_VIA_ALARM:
1421     if (eval { alarm($timeout); 1; }) {
1422         # Load POSIX if available
1423         eval { require POSIX; };
1424
1425         # Alarm handler will do the actual 'killing'
1426         $SIG{'ALRM'} = sub {
1427             select(STDERR); $| = 1;
1428             _diag($timeout_msg);
1429             POSIX::_exit(1) if (defined(&POSIX::_exit));
1430             my $sig = $is_vms ? 'TERM' : 'KILL';
1431             kill($sig, $pid_to_kill);
1432         };
1433     }
1434 }
1435
1436 my $cp_0037 =   # EBCDIC code page 0037
1437     '\x00\x01\x02\x03\x37\x2D\x2E\x2F\x16\x05\x25\x0B\x0C\x0D\x0E\x0F' .
1438     '\x10\x11\x12\x13\x3C\x3D\x32\x26\x18\x19\x3F\x27\x1C\x1D\x1E\x1F' .
1439     '\x40\x5A\x7F\x7B\x5B\x6C\x50\x7D\x4D\x5D\x5C\x4E\x6B\x60\x4B\x61' .
1440     '\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\x7A\x5E\x4C\x7E\x6E\x6F' .
1441     '\x7C\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xD1\xD2\xD3\xD4\xD5\xD6' .
1442     '\xD7\xD8\xD9\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xBA\xE0\xBB\xB0\x6D' .
1443     '\x79\x81\x82\x83\x84\x85\x86\x87\x88\x89\x91\x92\x93\x94\x95\x96' .
1444     '\x97\x98\x99\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xC0\x4F\xD0\xA1\x07' .
1445     '\x20\x21\x22\x23\x24\x15\x06\x17\x28\x29\x2A\x2B\x2C\x09\x0A\x1B' .
1446     '\x30\x31\x1A\x33\x34\x35\x36\x08\x38\x39\x3A\x3B\x04\x14\x3E\xFF' .
1447     '\x41\xAA\x4A\xB1\x9F\xB2\x6A\xB5\xBD\xB4\x9A\x8A\x5F\xCA\xAF\xBC' .
1448     '\x90\x8F\xEA\xFA\xBE\xA0\xB6\xB3\x9D\xDA\x9B\x8B\xB7\xB8\xB9\xAB' .
1449     '\x64\x65\x62\x66\x63\x67\x9E\x68\x74\x71\x72\x73\x78\x75\x76\x77' .
1450     '\xAC\x69\xED\xEE\xEB\xEF\xEC\xBF\x80\xFD\xFE\xFB\xFC\xAD\xAE\x59' .
1451     '\x44\x45\x42\x46\x43\x47\x9C\x48\x54\x51\x52\x53\x58\x55\x56\x57' .
1452     '\x8C\x49\xCD\xCE\xCB\xCF\xCC\xE1\x70\xDD\xDE\xDB\xDC\x8D\x8E\xDF';
1453
1454 my $cp_1047 =   # EBCDIC code page 1047
1455     '\x00\x01\x02\x03\x37\x2D\x2E\x2F\x16\x05\x15\x0B\x0C\x0D\x0E\x0F' .
1456     '\x10\x11\x12\x13\x3C\x3D\x32\x26\x18\x19\x3F\x27\x1C\x1D\x1E\x1F' .
1457     '\x40\x5A\x7F\x7B\x5B\x6C\x50\x7D\x4D\x5D\x5C\x4E\x6B\x60\x4B\x61' .
1458     '\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\x7A\x5E\x4C\x7E\x6E\x6F' .
1459     '\x7C\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xD1\xD2\xD3\xD4\xD5\xD6' .
1460     '\xD7\xD8\xD9\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xAD\xE0\xBD\x5F\x6D' .
1461     '\x79\x81\x82\x83\x84\x85\x86\x87\x88\x89\x91\x92\x93\x94\x95\x96' .
1462     '\x97\x98\x99\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xC0\x4F\xD0\xA1\x07' .
1463     '\x20\x21\x22\x23\x24\x25\x06\x17\x28\x29\x2A\x2B\x2C\x09\x0A\x1B' .
1464     '\x30\x31\x1A\x33\x34\x35\x36\x08\x38\x39\x3A\x3B\x04\x14\x3E\xFF' .
1465     '\x41\xAA\x4A\xB1\x9F\xB2\x6A\xB5\xBB\xB4\x9A\x8A\xB0\xCA\xAF\xBC' .
1466     '\x90\x8F\xEA\xFA\xBE\xA0\xB6\xB3\x9D\xDA\x9B\x8B\xB7\xB8\xB9\xAB' .
1467     '\x64\x65\x62\x66\x63\x67\x9E\x68\x74\x71\x72\x73\x78\x75\x76\x77' .
1468     '\xAC\x69\xED\xEE\xEB\xEF\xEC\xBF\x80\xFD\xFE\xFB\xFC\xBA\xAE\x59' .
1469     '\x44\x45\x42\x46\x43\x47\x9C\x48\x54\x51\x52\x53\x58\x55\x56\x57' .
1470     '\x8C\x49\xCD\xCE\xCB\xCF\xCC\xE1\x70\xDD\xDE\xDB\xDC\x8D\x8E\xDF';
1471
1472 my $cp_bc = # EBCDIC code page POSiX-BC
1473     '\x00\x01\x02\x03\x37\x2D\x2E\x2F\x16\x05\x15\x0B\x0C\x0D\x0E\x0F' .
1474     '\x10\x11\x12\x13\x3C\x3D\x32\x26\x18\x19\x3F\x27\x1C\x1D\x1E\x1F' .
1475     '\x40\x5A\x7F\x7B\x5B\x6C\x50\x7D\x4D\x5D\x5C\x4E\x6B\x60\x4B\x61' .
1476     '\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\x7A\x5E\x4C\x7E\x6E\x6F' .
1477     '\x7C\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xD1\xD2\xD3\xD4\xD5\xD6' .
1478     '\xD7\xD8\xD9\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xBB\xBC\xBD\x6A\x6D' .
1479     '\x4A\x81\x82\x83\x84\x85\x86\x87\x88\x89\x91\x92\x93\x94\x95\x96' .
1480     '\x97\x98\x99\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xFB\x4F\xFD\xFF\x07' .
1481     '\x20\x21\x22\x23\x24\x25\x06\x17\x28\x29\x2A\x2B\x2C\x09\x0A\x1B' .
1482     '\x30\x31\x1A\x33\x34\x35\x36\x08\x38\x39\x3A\x3B\x04\x14\x3E\x5F' .
1483     '\x41\xAA\xB0\xB1\x9F\xB2\xD0\xB5\x79\xB4\x9A\x8A\xBA\xCA\xAF\xA1' .
1484     '\x90\x8F\xEA\xFA\xBE\xA0\xB6\xB3\x9D\xDA\x9B\x8B\xB7\xB8\xB9\xAB' .
1485     '\x64\x65\x62\x66\x63\x67\x9E\x68\x74\x71\x72\x73\x78\x75\x76\x77' .
1486     '\xAC\x69\xED\xEE\xEB\xEF\xEC\xBF\x80\xE0\xFE\xDD\xFC\xAD\xAE\x59' .
1487     '\x44\x45\x42\x46\x43\x47\x9C\x48\x54\x51\x52\x53\x58\x55\x56\x57' .
1488     '\x8C\x49\xCD\xCE\xCB\xCF\xCC\xE1\x70\xC0\xDE\xDB\xDC\x8D\x8E\xDF';
1489
1490 my $straight =  # Avoid ranges
1491     '\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F' .
1492     '\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F' .
1493     '\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2A\x2B\x2C\x2D\x2E\x2F' .
1494     '\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3A\x3B\x3C\x3D\x3E\x3F' .
1495     '\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4A\x4B\x4C\x4D\x4E\x4F' .
1496     '\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5A\x5B\x5C\x5D\x5E\x5F' .
1497     '\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6A\x6B\x6C\x6D\x6E\x6F' .
1498     '\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7A\x7B\x7C\x7D\x7E\x7F' .
1499     '\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F' .
1500     '\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F' .
1501     '\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF' .
1502     '\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF' .
1503     '\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF' .
1504     '\xD0\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xDB\xDC\xDD\xDE\xDF' .
1505     '\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF' .
1506     '\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xFF';
1507
1508 # The following 2 functions allow tests to work on both EBCDIC and
1509 # ASCII-ish platforms.  They convert string scalars between the native
1510 # character set and the set of 256 characters which is usually called
1511 # Latin1.
1512 #
1513 # These routines don't work on UTF-EBCDIC and UTF-8.
1514
1515 sub native_to_latin1($) {
1516     my $string = shift;
1517
1518     return $string if ord('^') == 94;   # ASCII, Latin1
1519     my $cp;
1520     if (ord('^') == 95) {    # EBCDIC 1047
1521         $cp = \$cp_1047;
1522     }
1523     elsif (ord('^') == 106) {   # EBCDIC POSIX-BC
1524         $cp = \$cp_bc;
1525     }
1526     elsif (ord('^') == 176)  {   # EBCDIC 037 */
1527         $cp = \$cp_0037;
1528     }
1529     else {
1530         die "Unknown native character set";
1531     }
1532
1533     eval '$string =~ tr/' . $$cp . '/' . $straight . '/';
1534     return $string;
1535 }
1536
1537 sub latin1_to_native($) {
1538     my $string = shift;
1539
1540     return $string if ord('^') == 94;   # ASCII, Latin1
1541     my $cp;
1542     if (ord('^') == 95) {    # EBCDIC 1047
1543         $cp = \$cp_1047;
1544     }
1545     elsif (ord('^') == 106) {   # EBCDIC POSIX-BC
1546         $cp = \$cp_bc;
1547     }
1548     elsif (ord('^') == 176)  {   # EBCDIC 037 */
1549         $cp = \$cp_0037;
1550     }
1551     else {
1552         die "Unknown native character set";
1553     }
1554
1555     eval '$string =~ tr/' . $straight . '/' . $$cp . '/';
1556     return $string;
1557 }
1558
1559 sub ord_latin1_to_native {
1560     # given an input code point, return the platform's native
1561     # equivalent value.  Anything above latin1 is itself.
1562
1563     my $ord = shift;
1564     return $ord if $ord > 255;
1565     return ord latin1_to_native(chr $ord);
1566 }
1567
1568 sub ord_native_to_latin1 {
1569     # given an input platform code point, return the latin1 equivalent value.
1570     # Anything above latin1 is itself.
1571
1572     my $ord = shift;
1573     return $ord if $ord > 255;
1574     return ord native_to_latin1(chr $ord);
1575 }
1576
1577 1;