官术网_书友最值得收藏!

Typed variables

In the previous examples, the type of the content that is hosted in a variable container was defined by the value that was assigned to a variable:

my $x;      # Declaring a variable as a container.
$x = 2; # Now it contains an integer.
$x = 'Two'; # But now it keeps a string.

Perl 6 allows you to make the type of the variable container strict by specifying it together with a variable declaration:

my Int $x = 2;

Here, the $x variable will only be able to accept integers. An attempt to assign it to a string, for example, will result in the following error:

$x = 'Two'; # Type check failed in assignment to $x; 
# expected Int but got Str ("Two")

Similarly, Perl 6 allows elements of different types in the same array:

my @a = (1, 'two', 3.0);

Declaring an array with a type makes its element typed values. This means that you cannot assign a value of another type to it, as shown in the next example:

my Int @a;
@a = 1, 2, 3;
say @a;
@a[2] = 'Two';

The last assignment causes the type check error:

Type check failed in assignment to @a; expected Int   
but got Str ("Two")
in block <unit> at typed-arr.pl line 7

Typed variables can use any of the built-in types or user-defined classes. In the next section, we will talk about the data types available in Perl 6 by default. In Chapter 8, Object-Oriented Programming, you will learn how to create your own classes.

主站蜘蛛池模板: 新巴尔虎左旗| 乌恰县| 舞钢市| 郸城县| 雷州市| 辽宁省| 北辰区| 万山特区| 昭苏县| 德江县| 余干县| 乌拉特前旗| 喀喇沁旗| 天津市| 玛曲县| 怀远县| 油尖旺区| 临澧县| 星子县| 民勤县| 万荣县| 尉氏县| 洪洞县| 昌乐县| 达日县| 淄博市| 方正县| 延川县| 巴马| 略阳县| 嘉荫县| 松潘县| 兰溪市| 隆昌县| 丰城市| 泸溪县| 佛山市| 普定县| 修武县| 余干县| 梨树县|