What's the deal with all the different Perl 6 equality operators? (==, ===, eq, eqv, ~~, =:=, …)

前端 未结 4 1029
臣服心动
臣服心动 2021-01-31 08:15

Perl 6 seems to have an explosion of equality operators. What is =:=? What\'s the difference between leg and cmp? Or eqv and

4条回答
  •  抹茶落季
    2021-01-31 08:30

    =:= tests if two containers (variables or items of arrays or hashes) are aliased, ie if one changes, does the other change as well?

    my $x;
    my @a = 1, 2, 3;
    # $x =:= @a[0] is false
    $x := @a[0];
    # now $x == 1, and $x =:= @a[0] is true
    $x = 4;
    # now @a is 4, 2, 3 
    

    As for the others: === tests if two references point to the same object, and eqv tests if two things are structurally equivalent. So [1, 2, 3] === [1, 2, 3] will be false (not the same array), but [1, 2, 3] eqv [1, 2, 3] will be true (same structure).

    leg compares strings like Perl 5's cmp, while Perl 6's cmp is smarter and will compare numbers like <=> and strings like leg.

    13 leg 4   # -1, because 1 is smaller than 4, and leg converts to string
    13 cmp 4   # +1, because both are numbers, so use numeric comparison.
    

    Finally ~~ is the "smart match", it answers the question "does $x match $y". If $y is a type, it's type check. If $y is a regex, it's regex match - and so on.

提交回复
热议问题