This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Use alternative URLs for links which are now broken (link rot)
[perl5.git] / t / io / crlf.t
1 #!./perl -w
2
3 BEGIN {
4     chdir 't' if -d 't';
5     @INC = qw(. ../lib);
6 }
7
8 use Config;
9
10 require "test.pl";
11
12 my $file = tempfile();
13
14 if (find PerlIO::Layer 'perlio') {
15     plan(tests => 16);
16     ok(open(FOO,">:crlf",$file));
17     ok(print FOO 'a'.((('a' x 14).qq{\n}) x 2000) || close(FOO));
18     ok(open(FOO,"<:crlf",$file));
19
20     my $text;
21     { local $/; $text = <FOO> }
22     is(count_chars($text, "\015\012"), 0);
23     is(count_chars($text, "\n"), 2000);
24
25     binmode(FOO);
26     seek(FOO,0,0);
27     { local $/; $text = <FOO> }
28     is(count_chars($text, "\015\012"), 2000);
29
30     SKIP:
31     {
32         skip("miniperl can't rely on loading PerlIO::scalar")
33         if $ENV{PERL_CORE_MINITEST};
34         skip("no PerlIO::scalar") unless $Config{extensions} =~ m!\bPerlIO/scalar\b!;
35         require PerlIO::scalar;
36         my $fcontents = join "", map {"$_\015\012"} "a".."zzz";
37         open my $fh, "<:crlf", \$fcontents;
38         local $/ = "xxx";
39         local $_ = <$fh>;
40         my $pos = tell $fh; # pos must be behind "xxx", before "\nxxy\n"
41         seek $fh, $pos, 0;
42         $/ = "\n";
43         $s = <$fh>.<$fh>;
44         ok($s eq "\nxxy\n");
45     }
46
47     ok(close(FOO));
48
49     # binmode :crlf should not cumulate.
50     # Try it first once and then twice so that even UNIXy boxes
51     # get to exercise this, for DOSish boxes even once is enough.
52     # Try also pushing :utf8 first so that there are other layers
53     # in between (this should not matter: CRLF layers still should
54     # not accumulate).
55     for my $utf8 ('', ':utf8') {
56         for my $binmode (1..2) {
57             open(FOO, ">$file");
58             # require PerlIO; print PerlIO::get_layers(FOO), "\n";
59             binmode(FOO, "$utf8:crlf") for 1..$binmode;
60             # require PerlIO; print PerlIO::get_layers(FOO), "\n";
61             print FOO "Hello\n";
62             close FOO;
63             open(FOO, "<$file");
64             binmode(FOO);
65             my $foo = scalar <FOO>;
66             close FOO;
67             print join(" ", "#", map { sprintf("%02x", $_) } unpack("C*", $foo)),
68             "\n";
69             ok($foo =~ /\x0d\x0a$/);
70             ok($foo !~ /\x0d\x0d/);
71         }
72     }
73 }
74 else {
75     skip_all("No perlio, so no :crlf");
76 }
77
78 sub count_chars {
79     my($text, $chars) = @_;
80     my $seen = 0;
81     $seen++ while $text =~ /$chars/g;
82     return $seen;
83 }