Sun, 28 Sep 2008

Comparing and Matching

Permanent link


"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 (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. In the case of containers (like Array or Hash), the contents are compared with eqv. Two identically constructed data structures are equivalent.

Smart matching

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.


[/perl-5-to-6] Permanent link