Posts in this category
- Strings, Arrays, Hashes;
- Basic Control Structures
- Subroutines and Signatures
- Objects and Classes
- Regexes (also called "rules")
- Comparing and Matching
- Containers and Values
- Where we are now - an update
- Changes to Perl 5 Operators
- Custom Operators
- The MAIN sub
- Regexes strike back
- A grammar for (pseudo) XML
- Subset Types
- The State of the implementations
- Quoting and Parsing
- The Reduction Meta Operator
- The Cross Meta Operator
- Exceptions and control exceptions
- Common Perl 6 data processing idioms
Sun, 28 Sep 2008
Comparing and Matching
"Perl 5 to 6" Lesson 09 - Comparing and Matching
"ab" eq "ab" True "1.0" eq "1" False "a" == "b" failure, because "a" isn't numeric "1" == 1.0 True 1 === 1 True [1, 2] === [1, 2] False $x = [1, 2]; $x === $x True $x eqv $x True [1, 2] eqv [1, 2] True 1.0 eqv 1 False 'abc' ~~ m/a/ Match object, True in boolean context 'abc' ~~ Str True 'abc' ~~ Int False Str ~~ Any True Str ~~ Num False 1 ~~ 0..4 True -3 ~~ 0..4 False
Perl 6 still has string comparison operators (
cmp is now called
leg) that evaluate their operands in string context. Similarly all the numeric operators from Perl 5 are still there.
Since objects are more than blessed references, a new way for comparing them is needed.
=== returns only true for identical values. For immutable types like numbers or Strings that is a normal equality tests, for other objects it only returns
True if both variables refer to the same object (like comparing memory addresses in C++).
eqv tests if two things are equivalent, ie if they are of the same type and have the same value. In the case of containers (like
Hash), the contents are compared with
eqv. Two identically constructed data structures are equivalent.
Perl 6 has a "compare anything" operator, called "smart match" operator, and spelled
~~. It is asymmetrical, and generally the type of the right operand determines the kind of comparison that is made.
For immutable types it is a simple equality comparison. A smart match against a type object checks for type conformance. A smart match against a regex matches the regex. Matching a scalar against a
Range object checks if that scalar is included in the range.
There are other, more advanced forms of matching: for example you can check if an argument list (
Capture) fits to the parameter list (
Signature) of a subroutine, or apply file test operators (like
-e in Perl 5).
What you should remember is that any "does $x fit to $y?"-Question will be formulated as a smart match in Perl 6.