This file was automatically generated from http://svn.pugscode.org/pugs/docs/blog/02-types.pod on Sat Aug 1 14:01:17 2009 GMT, revision 27701.
"Perl 5 to 6" Lesson 02 - Types
my Int $x = 3;
$x = "foo"; # error
say $x.WHAT; # 'Int'
# check for a type:
if $x ~~ Int {
say '$x contains an Int'
}
Perl 6 has types. Everything is an Object in some way, and has a type. Variables can have type constraints, but they don't need to have one.
There are some basic types that you should know about:
'a string' # Str
2 # Int
3.14 # Num
(1, 2, 3) # List
All "normal" builtin types begin with an upper case letter. All "normal" types
inherit from Any, and absolutely everything inherits from Object.
You can restrict the type of values that a variable can hold by adding the type name to the declaration.
my Num $x = 3.4;
my Int @a = 1, 2, 3;
It is an error to try to put a value into a variable that is of a "wrong" type (ie neither the specified type nor a subtype).
A type declaration on an Arrray is used for its contents, so my Str @s is
an array that can only contain strings.
You can learn about the direct type of a thing by calling its .WHAT method.
say "foo".WHAT; # Str
However if you want to check if something is of a specific type, there is a different way, which also takes inheritance into account and is therefore recommended:
if $x ~~ Int {
say 'Variable $x contains an integer';
}
The type system isn't very easy to grok in all its details, but there are good reasons why we need types: