Typed hashes in Perl 6

Typed hashes in Perl 6

在 Perl 6 中, 你可以通过指定变量的类型来限制变量容器的内容, 例如:

my Int $i;

标量变量中只有一个值。你可以将该概念扩展到数组, 并让其元素仅保存整数, 如下例所示:

> my Int @i;
[]

> @i.push(42);
[42]

> @i.push('Hello');
Type check failed in assignment to @i;
expected Int but got Str ("Hello")
  in block <unit> at <unknown file> line 1

哈希中保存的是 pairs, 所以你可以同时指定键和值的类型。语法和上面的例子并无不同。

首先, 让我们声明值的类型:

my Str %s;

现在, 可以将字符串作为哈希的值:

> %s<Hello> = 'World'
World

> %s<42> = 'Fourty-two'
Fourty-two

但这个哈希不能保存整数:

> %s<x> = 100
Type check failed in assignment to %s;
expected Str but got Int (100)
  in block <unit> at <unknown file> line 1

(顺便提一下, 在 %s<42> 的情况下, 键是一个字符串。)

要指定第二个维度的类型, 即散列键的类型, 请在花括号中指定键的类型:

my %r{Rat};

这个变量也被称为对象散列(object hash)。

有了这个, Perl 允许使用 Rat 类型作为键:

> %r<22/7> = pi
3.14159265358979

> %r
{22/7 => 3.14159265358979}

尝试使用整数或字符串作为键则会失败, 例如:

> %r<Hello> = 1
Type check failed in binding to parameter 'key';
expected Rat but got Str ("Hello")
  in block <unit> at <unknown file> line 1

> %r{23} = 32
Type check failed in binding to parameter 'key';
expected Rat but got Int (23)
  in block <unit> at <unknown file> line 1

最后, 你可以同时指定键和值的类型:

my Str %m{Int};

此变量可用于将月份编号转换为月份名称, 但反过来不行:

> %m{3} = 'March'
March

> %m<March> = 3
Type check failed in binding to parameter 'key';
expected Int but got Str ("March")
  in block <unit> at <unknown file> line 1
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容