Categories
Posts in this category
- Introduction
- Strings, Arrays, Hashes;
- Types
- Basic Control Structures
- Subroutines and Signatures
- Objects and Classes
- Contexts
- Regexes (also called "rules")
- Junctions
- Comparing and Matching
- Containers and Values
- Where we are now - an update
- Changes to Perl 5 Operators
- Laziness
- Custom Operators
- The MAIN sub
- Twigils
- Enums
- Unicode
- Scoping
- 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
- Currying
Sun, 28 Sep 2008
Comparing and Matching
Permanent link
NAME
"Perl 5 to 6" Lesson 09 - Comparing and Matching
SYNOPSIS
"ab" eq "ab" True
"1.0" eq "1" False
"a" == "b" True
"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/ True
'abc' ~~ Str True
'abc' ~~ Int False
Str ~~ Any True
Str ~~ Num False
1 ~~ 0..4 True
-3 ~~ 0..4 False
DESCRIPTION
Perl 6 still has string comparison operators (eq, lt, gt, le, ge, ne; 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. Two identically constructed data structures are equivalent.
Smart matching
Perl 6 has a "compare everything" operator, called "smart match" operator, and spelled ~~.
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.