|
このページは大阪弁化フィルタによって翻訳生成されたんですわ。 |
|
NOTE: this is a rough draft of some initial, "all-encompassing" documentation for Perl6, written so that newcomers to Perl6, and Perl in general, can easily understand it. Note that the first draft originally at this location has been temporarily moved to here, if you're looking for it. I don't recommend it, however. Note that this is very detailed stuff, and so some of the details described herein are not necessarily accurate -- many have yet to be finalized! I will update each ASAP as individual decisions are made. Questions, corrections, and general feedback are gratefully accepted -- please email me at mlazzaro@cognitivity.com. At the core of any program is the manipulation of data. Whether the data is a mere set of bits, a document from a word processor, an image, the human genome, or anything else, the abstract goal is the same: to do something with that data. In order to manipulate data, however, we must first define what it is that we're manipulating. Generally, programmers tend to talk about the type and the value of data.
In general, the type and the value of the variable travel together. When programmers talk about the value of a variable, they most often mean the typed value -- the pairing of data type and data value that comprises, for the computer, what "thing" it's supposed to be working with. (mjl -- need to explain defined-ness somewhere in here, too.) Perl has a large number of builtin types, as well as the capability to add user-defined types. In general, however, all types belong to one of four broad "families":
Scalar is by far the most encompassing of the four. A variable or value is a scalar if it is not an array, a hash, or code. As you'll see later, that's quite a broad definition. VariablesIf values are just things, variables are simply the names of containers for those things. You can put things in each container, and you can take things out of each container. Some of these containers are tailored to accept only certain types of values, while others are more liberal in what can be placed inside them. You can name each container anything you want, like "shoes" or "fish", in order to differentiate it from all the others you might have around. In Perl, variable names always start with a special punctuation character, called a sigil. The sigil acts as a "signal" to Perl (and a reminder to you) that you will always be using the variable in a particular way, e.g. according to one of the four "fundamental" Perl types. There are four Perl sigils: The sigil is a part of the name of the variable -- they're always used together. Because of this, you can even have different variables that have the same name, except for different sigils:
Naming Variables:
Variable names must always start with a sigil, and may contain only alphanumeric characters (including Unicode characters!) and the underline character, The following are all valid variable names:
but these are not:
Scope: Variables also have a scope: that is, a specific region of the program in which they are visible. When a variable can be seen from anywhere within the program, it is called global. When a variable can only be seen from within a certain area of the program, it is called lexical. (You may also run into the term lexically scoped globals, which basically means lexical, but with a broader scope than most lexicals.) Truly global variables are generally avoided whenever possible, because it's easy to clutter up the global namespace with variables that most of the program doesn't need, and (worse) it's very easy for two separate parts of the program to, accidentally, pick the same variable name to do two different things, creating bugs that can be very difficult to find. There are three major scope declarators that you will use in Perl:
my, our, and temp in more detail later. First, let's describe how you use variables and values in general.
Declaring Variables and Assigning Values
Now let's look at a very small, very basic Perl statement.
This statement delares a new lexical variable named $i, which can only store values with the data type int. It then assigns the literal value 5 as the initial value of the variable. There are several things going on here, so we'll break it down into even smaller pieces.
This statement, as we saw in the last section, simply declares a new lexical variable named The next statement associates a specific data type with the new lexical variable
The int part declares that you will only be putting integer values into $i. If you try to place some other type of value into $i, it will attempt to convert the value to an integer. If it can, it will place the new, integer value into the variable. If it can't, it will generate an exception, warning you of the fact.
The It just so happens that the literal value
This happens because Perl knows that We've stated that a value may be converted to a value of another type based on the context in which it appears. Now let's formalize the notion of context more completely. Context refers to the type of value that Perl expects to use in any given situation. For example, a conditional statement like:
expects to operate on a boolean value (either true or false.) If the tested condition is true, the code inside the { ... } block will be executed; otherwise, it won't be. In order to use the variable $var inside an if statement, therefore, the value of $var must be used in boolean context -- it must be convertable to a boolean, and it is that boolean value which will then be tested by the if statement.
Similarly, if you are adding two values together:
you are operating in numeric context. Since the operator + expects to treat both sides as numbers, both $var1 and $var2 are evaluated in numeric context -- that is, converted to numbers -- before the addition of those numbers can take place.
If you print a variable or value, you are using string context:
so the value of $var is converted to a string, if possible.
In a nutshell, that's all that is meant by the notion of context. Context is just the data type that is expected, as opposed to the data type the current value actually is. There is, not surprisingly, a context for every type that exists in perl:
$var1 and $var2 are considered to be both in numeric context, and in scalar context.
Void Context: There is one other context, called void context, that represents that no data type at all is expected -- if one is provided, it would simply be thrown away. For example:
This is especially useful when declaring functions or methods, where you can check to see what context your function is being called in -- if it's void context, you know that the caller is just going to throw your return value away. Maybe that means you shouldn't bother calculating a return value in those cases, or maybe it even means you should throw an exception, to vigorously warn the caller that not checking your return value is an exceptionally bad idea.
Most of the time, you won't be worrying about the context, since Perl will convert values from the current type to the required contextual type automatically, as long as it can find a way to do so. There are occasions, however, where you explicitly want to treat a variable or value as being in a certain context. You can do this through typecasting. TypecastingTypecasting is the conversion from a value of one type to a value of another type. In Perl, typecasting happens automatically in most situations. For those occasions when you specifically want a value to be evaluated in a way different from what the context of the value implies, you can use an explicit typecast by specifying a type name before the value:
The typecasting syntax is type expression or type(expression), so you may typecast the value returned by any expression, not just simple terms like the above. Note that typecasting returns a value of the requested type, but it doesn't change the value of the thing it's operating on -- in the last example, the variable $myObject isn't altered. If the value is already the requested type, the statement is a noop -- an operation that doesn't do anything at all.
You generally use typecasting to force the context in which a value or expression is evaluated. For example:
Not all typecasts are possible: that is, values can't necessarily be converted from one type into every other possible type. In general, Perl's builtin types have all the most useful conversions predefined, but if you're attempting to typecast to or from your own object classes, you'll first have to set your classes up to support those typecasts. Perl will always look for the "best" translation between typed values, but if no possible translation exists, an exception will be thrown. Binding (Aliasing) VariablesBinding is different from assignment. While assignment copies the value of whatever's on the right side, and places it in the variable on the left side, binding makes variable on the left side point to the same "container" as the variable on the right side. The binding operator is
If the variable on the right side changes in value, the variable on the left side will change, too:
This has the practical effect of making the variable $b an alias for the variable $a. As we will see later, the list form of binding is especially useful, since it allows you to swap the contents of variables:
Properties
(mjl-- I don't think this section even needs to be here. May want to delay property introductions until later.) Values and variables may also have properties attached to them, which are essentially "out-of-band" notes on how the value or variable should behave. They don't change what the value or variable is, they just change how it will act. Properties on variables are frequently called compiletime or fixed properties, because they are a part of the declaration of the variable: you can't change them afterwards. Fixed properties are declared using the keyword
Properties on values are called runtime or dynamic properties, because they may change at runtime. Dynamic properties are assigned using the keyword
You can also define your own fixed and dynamic properties. We'll explain the details in later chapters: for now, just be aware that properties can exist.
Builtin Scalar Types Perl has the following builtin scalar types. Some types have two names: the first refers to the primitive type, which is what you will use most of the time. The second name is the promoted type, or full object type: this is the name for a larger version of the object that may have associated methods, properties, and other object-oriented accoutrements. Don't worry about the promoted type names just yet, we'll get to them later.
Declaring Scalars:
To declare a scalar variable, use the
Boolean Types, bool and Bool
The
Boolean values and variables are extremely compact and efficient, so if you're defining a variable, and you know that the value of it will never be anything other than true or false, you should make it a boolean:
Note that we didn't give an initial value to two of the above statements. A bool that is not specifically true is always assumed to be false, so the above is equivalent to:
A primitive type like a
the variable is automatically set to 0. If you don't want this behavior, you can use the promoted boolean type, Bool. A Bool value can be undefined:
Because promoted types like Bool are slightly larger and slower than their primitive counterparts like bool, you should get in the habit of using the primitive varieties whenever possible, and only using the promoted types when that's what you really mean.
What is Truth?: The notions of true and false are fairly liberal in Perl. In general, any scalar value is considered true except for the following:
Perl allows any value to be true or false however. You can attach but true or but false declarations to any value to specifically enforce the "truth" of that particular value.
Note that the bool type and the bit type that we will introduce later are therefore not synonymous, and may not be used interchangeably. A bit is a numeric type that stores an integer value, 1 or 0: it corresponds to a single computer "bit". A bool stores conceptual truth or falseness. Unlike many other languages, Perl allows a 0 value (usually considered false) to sometimes be true, and a 1 value (usually true) to be false! This usage is typically quite rare, but if you are ever given a value that is "0 but true", or "1 but false", you'll want to very clearly distinguish between the value (1 or 0) and the boolean truth (true or false). So use bool when you mean truth, and bit when you mean a numeric 1 or 0.
Typecasting Between Boolean Operators: A number of operators exist in Perl for manipulating boolean values. We'll explain them more fully in a later chapter, but these are the most common ones:
For more details, see the chapter on Operators.
Numeric Types
The primary numeric types in Perl are
If you don't assign a value to an int or num, it defaults to the value 0. Like all primitive types, you cannot set them to the undefined value, undef. If that's a problem, you should use their equivalent promoted types, Int and Num.
Literal Numbers:
Literal numbers in Perl can be expressed in a variety of ways. Perl understands decimal, scientific, binary, octal, and hexidecimal representations of numbers, as well as
The terms +Inf and -Inf represent positive and negative infinity; you may sometimes use these to create infinite lists. The value NaN ("Not a Number") may be returned by some functions or operations to represent that the result of a calculation (for example, division by zero) cannot be represented by a numeric value.
Perl allows the underline character,
You can even specify numbers using a base other than the usual 10, 2, 8, or 16 by specifying an explicit radix before the number, using a colon:
Note that you can specify hexidecimal (base 16) values (and values in any other base lower than 37) using either uppercase or lowercase A-F. This is because Perl uses the following digit mappings when using non-standard radix specifications:
You cannot specify a radix above 62, because Perl wouldn't have enough alphanumeric characters to represent it. You'd have to program something like that on your own.
Assigning Values to Numeric Types:
When typing a literal number like any of the above, you generally don't specify the exact type of the number, because Perl can determine it from the surrounding context. When you state a literal number in a context where Perl can't be sure what numeric type you intend to create, Perl will usually create the number as a
How you write a literal number doesn't affect the type of the number. You can write a literal number in any format you wish, it will still be treated as whatever type the context dictates. That's why you can specify:
and $n will be assigned the integer value 12 in each case. Format does not affect type!
Converting Between Numeric Types: Perl performs automatic conversion between all numeric types, so you can easily convert numbers from one type to any other type.
There are two things to be aware of. First, if you try to assign a non-integer value to an int:
the value will be truncated to an integer. If you intended to round the number, you should do it explicitly:
Second, the conversion will only work if the destination type can handle a number in the range you've specified. If not, the number may be truncated or rounded to fit, or an exception may be thrown, depending on how that numeric type has been designed to deal with the situation. In general, however, you only have to worry about this when using very big, very small, or very, very precise floating point numbers.
Typecasting Between Numeric and Other Scalar Types: A numeric value may trivially converted to a boolean or string value simply by using it as such. When typecasting to a
When typecasting to a string, the value is always represented in integer, decimal, or exponential form, depending on how the number can best be represented:
(mjl -- need specific rules for deciding what "big" is in casting to string)
If you want to output a number as a hexidecimal or another specialized format, use Numeric Operators: There are a large number of operators in Perl that are designed to work with numeric values. We'll explain the Perl operators more fully in a later chapter, but these are the ones that are most common when working with numeric values. You will recognize most of them as being identical to those in C or other languages:
For more details, see the chapter on Operators.
Overflow and Out-Of-Range Errors: If you attempt to assign to a typed numeric variable a value that is too big to be represented in that type, Perl only has two choices: truncate the value so that it fits, or generate an exception warning you that the value doesn't fit. ... (mjl -- so which is it?) ... Precision:
Perl uses double-precision floating point numbers (frequently just called doubles) to represent the (mjl -- Note: probably should put a sidebar explaining float internals here.) What this essentially means that it's generally a bad idea to compare two floating point numbers for equality. (If you've been programming with floating point numbers in other programming languages, you probably already knew that.)
The correct way to compare two floating point numbers is to ask if they are within a desired range of one another. Specify a range that's small enough to accomplish your required degree of precision, but still large enough not to run into the precision boundaries of floating point representations:
None of these problems come up when you are simply testing floating point numbers to determine if one is greater than or less than another (unless your numbers are larger or smaller than floating point can represent, of course), only when testing for equality.
Promoted Types: Ints and Nums:
The promoted types of
The Full List of Numeric Types:
In addition to the standard
Each of these has a matching promoted type, which starts with a capital letter instead of a lowercase letter (e.g. The You typically won't declare anything as the (mjl -- more coming soon!)
|