perlpdl

How can I check if a Perl variable is in PDL format (i.e. is a piddle)?


I'm using PDL. If I am given variable $foo that can be a hash reference, an array reference, a scalar, or a piddle (which can be empty or null), how can I tell if it's a piddle?


Solution

  • The typical way to check if something is of a certain class is with isa.

    if( $thing->isa("PDL") ) { ... }
    

    This respects inheritance. So long as $thing is a subclass of PDL (or says it is) the above will work. This protects you both against custom subclasses and changes to PDL itself. Below is an example.

    use strict;
    use warnings;
    use v5.10;
    
    package MyPDL;
    our @ISA = qw(PDL);
    
    package main;
    
    use PDL;
    use Scalar::Util qw(blessed);
    
    my $stuff = pdl [1..10];
    
    say blessed $stuff;                                   # PDL
    say "\$stuff is a PDL thing" if $stuff->isa("PDL");   # true
    
    my $bar = MyPDL->new([1..10]);
    say blessed $bar;                                     # MyPDL
    say "\$bar is a PDL thing" if $bar->isa("PDL");       # true
    

    However, method calls don't work on non-references and unblessed references; you'll get an error if you try. You can work around this in two ways. First is to use eval BLOCK to trap the error, like try in another language.

    if( eval { $thing->isa("PDL") } ) { ... }
    

    If $thing is not an object, eval will trap the error and return false. If $thing is an object, it will call isa on it and return the result.

    The downside is this will trap any error, including an error from isa. Rare, but it happens. To avoid that, use Scalar::Util's blessed() to first determine if $thing is an object.

    use Scalar::Util qw(blessed):
    
    if( blessed $thing && $thing->isa("PDL") ) { ... }