|
Perl 6 FAQ - Operators
This FAQ is part of the Programmer's Heaven Perl 6 FAQ. It answers questions about operators in Perl 6, including changes and additions since Perl 5.Does Perl 6 really have unicode operators?
Yes, and it will be possible to define new ones too. For example, the Set module may define union and intersection operators using the usual mathematical symbols:$weapons = $guns$bombs; $illegal_weapons = $weapons
$ban_list;
Being able to add new operators helps to prevent the standard set of built-in operators from being overloaded with meanings that are completely unrelated to their standard behaviour. For example, the "+" operator may be overloaded in some languages to mean set union; if this happens, it is not obvious to someone reading the program what the operation is going to do. Once you learn an operator in Perl 6, you will be able to understand what it does no matter what types it is used with.
All of the built-in unicode operators have ASCII equivalents. Hopefully, all those who implement modules will be sensible enough to provide ASCII equivalents too.
What do the operators for arithmetic and logical operations look like in Perl 6?
Almost the same as in Perl 5, but with some new additions. Here are the infix operators (those that are placed between two operands, for example infix "+" would be written "$x + $y"):| + | Add |
| - | Subtract |
| * | Multiply |
| / | Divide |
| ** | Raise to power |
| || | Logical OR (short circuit) |
| && | Logical AND (short circuit) |
| ^^ | Logical XOR |
| or | Logical OR (short circuit), low precedence |
| and | Logical AND (short circuit, low precedence) |
| xor | Logical XOR (low precedence) |
| ?| (NEW) | Logical OR (does not short circuit, unlike ||) |
| ?& (NEW) | Logical AND (does not short circuit, unlike &&) |
And the prefix ones (those that have one operand and are placed before it, for example prefix "!" is written "!$x"):
| ! | Not |
| - | Negate |
| ++ | Pre-increment (that is, increment the operand and then evaluate it) |
| -- | Pre-decrement (that is, decrement the operand and then evaluate it) |
And the postfix ones (those that have one operand and are placed after it, for example postfix "++" is written "$x++"):
| ++ | Post-increment (that is, increment after the operand has been evaluated) |
| -- | Post-decrement (that is, decrement after the operand has been evaluated) |
What do the operators for comparison look like?
Exactly the same as they did in Perl 5 for numeric and string comparisons:| == | Numeric equality |
| <= | Numeric less than or equals |
| >= | Numeric greater than or equals |
| < | Numeric less than |
| > | Numeric greater than |
| != | Numeric inequality (not equal) |
| eq | String equality |
| le | String less than or equals |
| ge | String greater than or equals |
| lt | String less than |
| gt | String greater than |
There is also a way to check if two variables are aliases (bound with ":=" or "::=") to the same thing. This is the "=:=" operator, and is demonstrated in the following example.
my $a = "monkey";
my $b := $a;
my $c = "monkey";
if $a =:= $b {
say "a and b are aliases"; # Prints this...
}
if $a =:= $c {
say "a and c are aliases"; # ...but NOT this.
}What do string operations (such as concatenation) look like in Perl 6?
The "~" operator now does concatenation, replacing the "." operator in Perl 5.my $a = 'hello '; my $b = 'world'; say $a ~ $b; # hello world
The "x" operator does string repetition, as it does in Perl 5:
my $animal = 'badger '; my $annoying_song = $animal x 3; # badger badger badger
How is the ternary operator (" ? : ") written in Perl 6?
The ternary operator, found in many languages (Perl 5 included) in the form "condition ? iftrue : iffalse", is written as "condition ?? iftrue !! iffalse". If you have not seen the ternary operator before from other languages, it is essentially a way of writing simple conditionals in expressions rather than having to write an "if" block.This statement prints "correct" when $answer is 42 and wrong otherwise.
say $answer == 42 ?? 'correct' !! 'wrong';
What is the "~~" operator, or the smart match operator, or where on earth did Perl 5's "=~" go?
The Perl 5 "=~" operator for matching a regex against a string has now become "~~", also known as the smart match operator. The Perl 5 "does not match" operator, "!~", has become "!~~".my $text = 'There is a weasel in here.';
if $text ~~ /weasel/ {
say "Dude, we got a weasel!"; # This prints
}
if $text !~~ /banana/ {
say "We got no bananas." # This prints too
}The smart match operator does much more than matching regexes against strings; for more details, see the "Smart Match" table in the specification:
http://dev.perl.org/perl6/doc/design/syn/S03.html
What is the "//" (defined-or) operator?
For something to be defined, it must have had a value (other than undef) assigned to it.
It works very much like the short-circuit "||" (logical OR) operator, but instead of testing whether the value on the left evaluates to something that is considered true or false, it tests whether it is defined. For example:my $x; my $y = 0; my $z = 3; say $x || $z; # 3 - $x is undefined, which evaluates to false say $y || $z; # 3 - $y is zero, which evaluates to false say $x // $z; # 3 - $x is undefined say $y // $z; # 0 - $y is defined
What do bitwise operations look like in Perl 6?
A junction is a variable that can have many values at the same time.
In Perl 6, the "|", "&" and "^" operators, as seen in Perl 5 and many other C-like languages, are no longer bitwise operators; instead they are used to construct junctions. The bitwise operators in Perl 6 come in three forms, depending on whether you are applying them to strings, integers or booleans. | +| | Bitwise OR on numeric values |
| +& | Bitwise AND on numeric values |
| +^ | Bitwise XOR on numeric values |
| ~| | Bitwise OR on string values |
| ~& | Bitwise AND on string values |
| ~^ | Bitwise XOR on string values |
| ?| | Bitwise OR on booleans (a single bit) |
| ?& | Bitwise AND on booleans (a single bit) |
| ?^ | Bitwise XOR on booleans (a single bit) |
Notice how the first character defines the type of data that the operation is being performed on and the second the type of operation. These operators actually coerce values to the type specified by the first character, just like these characters do as unary coercion ops (see next question for more).
Doing a bitwise operation on a string will treat the entire string as a long stream of bits and operate per bit. Note that this is only allowed on strings containing chunks of binary data; doing these operations on a unicode string will not work out.
What are the number, string and boolean coercion operators (prefix "+", "~" and "?")?
Coercion could also be read as "conversion to another type". These operators force the conversion of a variable to a number, string or boolean. Note that the negation and not operators also causes such coercions to take place.| + | Coerce to number |
| - | Coerce to number and negate |
| ~ | Coerce to string |
| ? | Coerce to boolean |
| ! | Coerce to boolean and do a "not" |
Be aware that coercion is not just a change of type (known as casting), but involves changing the way data is represented too. Here are some examples.
my $int1 = 0; my $int2 = 42; my $string = "turbo"; say ?$int1; # no output say ?$int2; # a 1 say +$string; # no output - no number parsed from string
What is operator chaining?
Operator chaining, a new feature in Perl 6, allows a single operand to be involved in more than one comparison. For example, we can check if $x is a number between 1 and 10 (included) like this:if 1 <= $x <= 10 {
say "$x is between 1 and 10";
}You can read that as "if 1 is less than or equal to $x and $x is less than or equal to ten". In Perl 5 you would have had to write something like this:
if ($x >= 1 && $x <= 10) {
print "$x is between 1 and 10\n";
}You can create longer chains too.
if 1 <= $roll1 === $roll2 <= 6 {
say "You rolled doubles!";
}This verifies that $roll1 and $roll2 are equal, and that both are between 1 and 6 (including 1 and 6).
What is a list operator (or how is "5, 6, sort 8, 7" parsed)?
A list operator takes a list as an argument and produces a list as a result. When a list that includes a list operator is being parsed, all arguments following the operator are taken to be its operands (up to a closing bracket).For example, this code:
5, 6, sort 8, 7
Would end up with the sort operator taking both 8 and 7 as operands, producing the list:
5, 6, 7, 8
What is the zip operator?
The zip operator, written with a Z, is useful for iterating over two or more arrays in parallel. It builds an array of arrays, the first element being an array containing the first elements of the two zipped arrays and so on:(1,3,5) Z (2,4,6) # ((1, 2), (3, 4), (5, 6))
You can use this with a for loop:
my @names = ('Jack', 'Emma', 'Robert');
my @ages = (20, 19, 35);
for @names Z @ages -> [ $name, $age ] {
say "$name is $age years old";
}The output of the above program will be:
Jack is 20 years old. Emma is 19 years old. Robert is 35 years old.
You can also use the zip function instead of the operator; with this, the for line above becomes:
for zip(@names; @ages) -> [ $name, $age ] {An alternative is to use the each keyword, which build a flat array with the elements interleaved.
my @names = ('Jack', 'Emma', 'Robert');
my @ages = (20, 19, 35);
for each(@names; @ages) -> $name, $age {
say "$name is $age years old";
}This second example produces the same output as the first, and also works in Pugs at the time of writing.
What is the cross operator?
The cross operator builds a list of all permutations of the elements of the lists supplied to it. For example:my @a = (1, 2); my @b = (3, 4); my @c = @a X @b; # @c is ((1,3),(1,4),(2,3),(2,4))
The cross operator is associative, meaning that you can do:
my @a = (1, 2); my @b = (3,4); my @c = (5,6); my @d = @a X @b X @c;
This results in @d containing the 8 different permutations:
(1,3,5),(1,3,6),(1,4,5),(1,4,6),(2,3,5),(2,3,6),(2,4,5),(2,4,6)
The cross operator is actually a special case of the cross meta-operator, which is discussed later.
What is the hyper ("»...«" or ">>...<<") meta-operator?
The hyper meta-operator takes another operator and applies it, an element at a time, to an entire array. You can make any infix operator a hyper operator by placing a "»" to the left of it and a "«" to the right of it. If you are unable to type these characters then you can use the ASCII alternatives instead, which are ">>" and "<<".my @a = (1,2,3,4); my @b = (2,3,4,5); my @c = @a »+« @b; say join ",", @c; # 3,5,7,9 my @d = @a »*« @b; say join ",", @d; # 2,6,12,20
Notice that in the addition example, the first element of the resulting array (3) is the first elements of @a and @b (1 and 2) added together. The Perl 6 line:
my @c = @a »+« @b;
Could be approximated in Perl 5 like this:
my @c;
for (my $i = 0; $i < @a; $i++) {
$c[$i] = $a[$i] + $b[$i];
}You can modify the original values of @a to have the results using ">>+=<<", just as you would use "+=" to add to an existing value.
my @a = (1,2,3,4); my @b = (2,3,4,5); @a »+=« @b; # Modifies @a say join ",", @a; # 3,5,7,9
For unary operators (that is, ones that only have a single operand, such as the post-increment operator "++"), you just use the "»" or "«", pointing the "fat end" towards the array.
my @a = (1,2,3,4); @a»++; say join ",", @a; # 2,3,4,5 say join ",", -«@a; # -2,-3,-4,-5
What happens if hyper operators are applied to lists of lists?
If a hyper operator is applied to a list and within that list are other lists, then the hyper operator will recursively be applied to that list too. For example:my @a = (1, [2, 3], 4); @a»++; # @a is now (2, [3, 4], 5)
What happens if the lists on either side of a hyper operator are of different lengths or dimensions?
If you try and apply a hyper operator as shown in the previous question to two lists with different dimensions, it will throw an exception. You can request that a list on one or both sides of a hyper operator is "upgraded" to the correct dimensions by pointing the sharp end of the « or » at it.For example, to multiply every element of the array @a by 2, the single value 2 must be upgraded to a list of the same length of @a. You write this as follows:
my @a = (1,2,3,4); my @doublea = @a »*» 2; # Notice »*», not »*« say join ",", @doublea; # 2,4,6,8
If the hyper operator is being applied to two lists and you are unsure of whether they will have the same dimensions, but want Perl to upgrade them as needed, point the sharp end at either side, for example:
my @a = (1,2,3); my @b = (1); say join ",", @a «+» @b; # 2,3,4 say join ",", @b «+» @a; # 2,3,4 say join ",", @a »+« @b; # Exception say join ",", @b »+« @a; # Exception
What is the reduce ("[...]") meta-operator?
The reduce metaoperator could be seen as textually placing the given operator between each element of an array. For example, in the case of addition it will add all of the values in the array together.my @a = (1,2,3,4); say [+] @a; # 10 (1 + 2 + 3 + 4)
In Perl 5 this could have been written as:
my @a = (1,2,3,4);
my $temp = 0;
foreach (my $i = 0; $i < length(@a); $i++) {
$temp += $a[$i];
}
print "$temp\n";Alternatively, you could use it with the "<=" operator to ensure that an array is sorted in ascending order.
my @a = (5,3,8,10);
my @b = (3,5,8,10);
if [<=] @a {
say "a is sorted"; # This line does not get run
}
if [<=] @b {
say "b is sorted"; # Prints "b is sorted"
}What is the cross meta-operator?
Like the cross operator itself, the cross meta-operator produces all permuations of the elements of two lists. However, it also enables you to specify an operation to be performed between the values rather than just placing them into a list. For example, you could add them together.my @a = (1, 2); my @b = (3, 4); my @c = @a X+X @b; # @c is (1+3,1+4,2+3,2+4) = (4,5,5,6)
The cross meta-operator is associative, like the cross operator. In fact, the cross operator itself is really just a shorthand for X,X. X,X and X are equivalent because the , operator just concatenates two things into a list.
Back To FAQ List | Next Section
What's next?
Join our Perl 6 Newsletter
Visit our Perl Resources
- Perl 6 Forum
- Perl, PHP & Python zone
- Perl Programming Forum
- Beginners Guide to Perl
- Regex tutorial
- 20 Perl Tips And Tricks
|
|
riya
From India (Report as abusive) |
"Very Useful" this faqs made to know about many things unknown and it helped me a lot |
| View all Rate and comment this article |
Sponsored links
3 Months Free - ASP.NET Web Hosting
3 Months Free & No Setup Fees on ASP.NET 3.5/2.0 Hosting on Windows 2008/2003 Servers ? Click Here!
3 Months Free & No Setup Fees on ASP.NET 3.5/2.0 Hosting on Windows 2008/2003 Servers ? Click Here!
Build IT Knowledge with Current & Trusted Content
Helps Employees Develop & Hone New Technical Programming Skills. Sign Up & Get Full Access.
Helps Employees Develop & Hone New Technical Programming Skills. Sign Up & Get Full Access.
Check Out IT Certification Preparation Materials
Sign Up With SkillSoft & Get Access to Training Materials for Over 50 Professional Certifications.
Sign Up With SkillSoft & Get Access to Training Materials for Over 50 Professional Certifications.
SFTP components for .NET
Add complete SSH and SFTP support to your .NET framework application
Add complete SSH and SFTP support to your .NET framework application
Experience Adobe? FLASH MEDIA SERVER 3
Introducing the media solution for total action without interruption. TRY IT NOW FOR FREE!
Introducing the media solution for total action without interruption. TRY IT NOW FOR FREE!
$bombs;
$illegal_weapons = $weapons
$ban_list;