- Perl 6 Deep Dive
- Andrew Shitov
- 259字
- 2021-07-03 00:05:49
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.
- Spring 5.0 Microservices(Second Edition)
- Vue.js前端開發(fā)基礎(chǔ)與項(xiàng)目實(shí)戰(zhàn)
- JavaScript Unlocked
- Reactive Programming with Swift
- Java深入解析:透析Java本質(zhì)的36個(gè)話題
- 21天學(xué)通C++(第6版)
- 編譯系統(tǒng)透視:圖解編譯原理
- Python Data Analysis(Second Edition)
- Python機(jī)器學(xué)習(xí):手把手教你掌握150個(gè)精彩案例(微課視頻版)
- Service Mesh實(shí)戰(zhàn):基于Linkerd和Kubernetes的微服務(wù)實(shí)踐
- 遠(yuǎn)方:兩位持續(xù)創(chuàng)業(yè)者的點(diǎn)滴思考
- Penetration Testing with the Bash shell
- Python預(yù)測(cè)分析實(shí)戰(zhàn)
- HTML5移動(dòng)前端開發(fā)基礎(chǔ)與實(shí)戰(zhàn)(微課版)
- Microsoft Exchange Server 2016 PowerShell Cookbook(Fourth Edition)