/
IO.pm
139 lines (115 loc) · 2.92 KB
/
IO.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
class IO {
has $!PIO;
has $!ins;
multi method close() is export {
try {
?$!PIO.close()
}
$! ?? fail($!) !! Bool::True
}
multi method eof() is export {
?$!PIO.eof();
}
multi method get() is export {
my $x = $!PIO.readline;
fail if $.eof && $x eq '';
$!ins++;
$x.chomp;
}
multi method ins() {
$!ins;
}
multi method lines($limit = *) {
my $l = $limit ~~ Whatever ?? Inf !! $limit;
gather while !$.eof && $l-- > 0 {
my $line = $.get;
if $line.defined {
take $line;
}
}
}
multi method print(*@items) {
try {
for @items -> $item {
(pir::descalarref__PP($!PIO)).print($item);
}
}
$! ?? fail($!) !! Bool::True;
}
multi method printf($format, *@args) {
self.print(sprintf($format, |@args));
}
multi method say(*@items) {
self.print(@items, "\n");
}
multi method slurp() {
$!PIO.readall();
}
multi method t() {
$!PIO.isatty;
}
}
multi sub lines(IO $filehandle,
:$bin = False,
:$enc = 'Unicode',
:$nl = "\n",
:$chomp = True) {
fail 'Binary mode not supported yet' if $bin;
fail 'Encodings not supported yet' if $enc ne 'Unicode';
fail 'Fancy newlines not supported yet' if $nl ne "\n";
fail 'Lack of chomp not supported yet' if !$chomp;
$filehandle.lines();
}
multi sub print(Mu *@items) { $*OUT.print(@items); }
multi sub prompt($msg) {
print $msg;
$*IN.get;
}
multi sub say(Mu *@items) { $*OUT.say(@items); }
sub open($filename, :$r, :$w, :$a) {
my $mode = $w ?? 'w' !! ($a ?? 'wa' !! 'r');
my $PIO = pir::open__PSS($filename, $mode);
unless pir::istrue__IP($PIO) {
die("Unable to open file '$filename'");
}
$PIO.encoding('utf8');
IO.new(:$PIO)
}
sub close($handle) {
$handle.close()
}
sub slurp($filename) {
my $handle = open($filename, :r);
my $contents = $handle.slurp();
$handle.close();
$contents
}
sub unlink($filename) {
Q:PIR {
.local string filename_str
.local pmc filename_pmc, os
.local int status
filename_pmc = find_lex '$filename'
filename_str = filename_pmc
os = root_new ['parrot';'OS']
push_eh unlink_catch
os.'rm'(filename_str)
status = 1
goto unlink_finally
unlink_catch:
status = 0
unlink_finally:
pop_eh
%r = box status
}
}
# CHEAT: This function is missing a bunch of arguments,
# and should be more robust.
multi lines (Str $filename, Any $limit = *) {
my $fh = open $filename or fail "Unable to open $filename";
$fh.lines($limit);
}
multi sub printf($format, *@args) {
$*OUT.printf($format, |@args);
}
# vim: ft=perl6