Category: Perl6 Keywords: IO Perl6
my shoulder
Yap, I'm just back from the Shanghai pm meeting. great meeting and lovely guys. :)simple
因为 FILEHANDLE 将不再存在,而 Perl 6 中有一类型叫做 IO,所以我们一般用如下方法(IO 对象的方法)读取文件:my $out = open(">$filename"); # $out 的类型就是 IO, 下同
my $in = open($filename);
my $append = open(">>$filename");
读进来后我们将不用 <> 来获取行,而用如下方法获取:
my $line1 = readline($in); # 要读取所有行的话将 $line1 改为 @line1。下同 my $line2 = $in.readline(); my $line3 = = $in; # 注意不是 ==这是三种读取的方法,下面是简单的写入方法:
$out.print("... Its not over yet!\n"); # 追加的写入是一样的
关闭自然是:
$in.close;
for, while
一般推荐用 for 来写:for (=$fh) -> $line { # 或 for =$fh -> $line { 省略了那括号
while 的写法如下:
my $line; # 必须声明 $line
while ($line = = $fh) {
相比而言,for 有额外的好处就是限制了 $line 参数的作用域到它所属的块。( while 声明 的 $line 在块结束后还是继续存在的。)
注意:下面的写法将使 $line 为整个文件的内容:while =$*IN -> $line {
这是因为 = 在标量上下文里会做一 slurp, 将整个文件读取进来。
slurp
my $content = slurp $filename;$content 将是整个文件的内容。
DATA
我们在 Perl 5 中文件里可以有一句柄为 __DATA__, 在 Perl 6 中我们可以有很多个 DATA。语法结构是下面这样子,但我不确定以后会不会更改(pugs 目前还没实现这一功能)。=begin DATA LABEL1
LABEL1.1
LABEL1.2
LABEL1.3
=end DATA
=begin DATA LABEL2
LABEL2.1
LABEL2.2
=end DATA
# %=DATA<LABEL1>[0] 为 LABEL1.1
# 我们还可以缩写为 $=LABEL2[1] 为 LABEL2.2
prompts
在 Perl 5 中命令行参数获取我们一般用print "输入您的用户名"; $user = <>;Perl 6 中我们将用 prompts 命令行提示来获取:
$ARGS prompts("Search? "); # Perl 6
while (<$ARGS>) {
但这也不是定下来了,所以先不详细介绍,等定下来了我再补充说明。
句柄参数
我在 my Perl6 @Examples[3] 介绍过类型在子程序中的应用。在 Perl 5 中一般用 \*FH 来传递句柄,这不是很方便而且 Perl 6 中也不再有 * 这种 typeglob 类型。新的传递方法将简单的使用类型 IO, 结合上面的写个简单完整例子:
my $fh = open('>temp') or die $!;
&append_2($fh, "line1");
&append_2($fh, "line2");
$fh.close;
sub append_2(IO $fh, $str) {
$fh.print("$str in subroutine\n");
}
# file:temp
# line1 in subroutine
# line2 in subroutine
DIR
因为在 Apocalypse, Synopsis 里都没有提到操作 DIR 的事,所以默认跟 Perl 5 是一样的。my IO $dir; opendir($dir, '.'); my @files = readdir($dir); close($dir);我认为 OO 方式也是可以的。比如 $dir.opendir('.'); $dir.readdir(); $dir.close();