Add smartmatch support topic/smartmatch
Yuval Kogman [Mon, 21 Sep 2009 18:35:54 +0000 (21:35 +0300)]
Delegates to the `check` method of the type constraint, so that e.g.

    "foo" ~~ Str

returns true.

Unfortunately this doesn't actually work for when (Str) etc because that
checks if the return value of Str is true instead of whether $_ ~~ Str.

lib/MooseX/Types/TypeDecorator.pm
t/22_smartmatch.t [new file with mode: 0644]

index a94c5c3..d78621e 100644 (file)
@@ -41,6 +41,12 @@ use overload(
         my $union = Moose::Meta::TypeConstraint::Union->new(type_constraints=>\@tc);
         return Moose::Util::TypeConstraints::register_type_constraint($union);
     },
+    ( $] >= 5.010 ? (
+        '~~' => sub {
+            my ( $self, $value ) = @_;
+            $self->__type_constraint->check($value);
+        },
+    ) : () ),
     fallback => 1,
     
 );
diff --git a/t/22_smartmatch.t b/t/22_smartmatch.t
new file mode 100644 (file)
index 0000000..ef54192
--- /dev/null
@@ -0,0 +1,37 @@
+#!/usr/bin/perl
+
+use strict;
+use warnings;
+
+use Test::More;
+
+BEGIN {
+    plan skip_all => "5.10.0 required" unless eval { require 5.010 };
+    plan tests => 8;
+}
+
+use MooseX::Types::Moose qw(Str HashRef ArrayRef);
+
+use 5.010;
+
+ok( "foo" ~~ Str, "string" );
+ok( Str() ~~ "foo", "string" );
+ok( !("foo" ~~ HashRef), "hashref" );
+ok( !(HashRef() ~~ "foo"), "hashref" );
+
+sub foo {
+    given ($_[0]) {
+        # unfortunately we can't actually have when(HashRef) etc, because that
+        # resolves as a boolean (checks whether the return value of HashRef etc
+        # is true)
+        when ($_ ~~ HashRef)  { return "hash" }
+        when ($_ ~~ ArrayRef) { return "array" }
+        when ($_ ~~ Str)      { return "string" }
+        default               { return "something else" }
+    }
+}
+
+is( foo({}), "hash" );
+is( foo("foo"), "string" );
+is( foo([]), "array" );
+is( foo(sub { }), "something else" );