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