How do I tell what type of value is in a Perl variable?

前端 未结 5 2132
旧时难觅i
旧时难觅i 2020-12-02 16:52

How do I tell what type of value is in a Perl variable?

$x might be a scalar, a ref to an array or a ref to a hash (or maybe other things).

5条回答
  •  生来不讨喜
    2020-12-02 17:01

    I like polymorphism instead of manually checking for something:

    use MooseX::Declare;
    
    class Foo {
        use MooseX::MultiMethods;
    
        multi method foo (ArrayRef $arg){ say "arg is an array" }
        multi method foo (HashRef $arg) { say "arg is a hash" }
        multi method foo (Any $arg)     { say "arg is something else" }
    }
    
    Foo->new->foo([]); # arg is an array
    Foo->new->foo(40); # arg is something else
    

    This is much more powerful than manual checking, as you can reuse your "checks" like you would any other type constraint. That means when you want to handle arrays, hashes, and even numbers less than 42, you just write a constraint for "even numbers less than 42" and add a new multimethod for that case. The "calling code" is not affected.

    Your type library:

    package MyApp::Types;
    use MooseX::Types -declare => ['EvenNumberLessThan42'];
    use MooseX::Types::Moose qw(Num);
    
    subtype EvenNumberLessThan42, as Num, where { $_ < 42 && $_ % 2 == 0 };
    

    Then make Foo support this (in that class definition):

    class Foo {
        use MyApp::Types qw(EvenNumberLessThan42);
    
        multi method foo (EvenNumberLessThan42 $arg) { say "arg is an even number less than 42" }
    }
    

    Then Foo->new->foo(40) prints arg is an even number less than 42 instead of arg is something else.

    Maintainable.

提交回复
热议问题