Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a function parameter is a string or array in Perl

I'm trying to write a custom validateParameter function with Perl. I have the following code which also works:

sub validateParameter {
    my ($args, $list) = @_;
    
    if ( ref($list) eq "ARRAY" ) {

        foreach my $key (@$list) {
            if ( not defined $args->{$key} ) {
                die "no $key given!";
            }
        }
    } 
    #elsif ( check if string ) {
    #}
}

I want to call my function the following way:

validateParameter({ hallo => "Welt", test => "Blup"},  ["hallo", "test"]);

But I also want to call my function like this:

validateParameter({ hallo => "Welt", test => "Blup"},  "hallo");

I know that Perl only has the following three data-types (scalars, hashes, arrays). But maybe there is a smart way to check if a variable is a string.

How can I check if the given arg is a string?

like image 791
FrankTheTank_12345 Avatar asked Oct 27 '25 23:10

FrankTheTank_12345


1 Answers

Update: I somehow missed the end of the question. Just testing ref($list) eq 'ARRAY' will work most of the time, but to properly allow even overloaded objects, you should just try dereferencing the parameter:

if ( eval { \@$list } ) {
    # it was an array 
}
else {
    # assume it is a string
}

Original answer:

You can check a number of things about a parameter:

if ( ! defined $param ) {
    # undefined
}
elsif ( defined Scalar::Util::blessed($param) ) {
    # object
}
elsif ( ref $param ) {
    # reference (return of ref will give the type)
}
elsif ( length do { no warnings "numeric"; $param & '' } ) {
    # number
}
else {
    # string
}

But all of that (except perhaps the defined check) kind of defeats the purpose of Perl's automatically converting to your desired type and will limit what can be passed (for instance, a string or dualvar where a number is wanted, or an overloaded object where a string, number, or reference is wanted, or tied variables or magic variables such as $!).

You may want to also just look at what Params::Validate can do.

like image 86
ysth Avatar answered Oct 29 '25 18:10

ysth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!