Question

I'm writing a perl subroutine and I would like to have the flexibility to either pass in values as a hash, or just as single values. I would like to know how the arguments are passed to the subroutine, so that I can handle the cases separately. For example:

#case 1, pass in hash
test(arg1 => 'test', arg2 => 'test2');

#case 2, just pass in single values
test('test', 'test2');

sub test { 
    #if values passed in as a hash, handle one way
    if(...) { 

    }
    #if values passed in as single values, do something else
    else { 

    }
}

Is there a way to detect this in perl? Thanks!

Was it helpful?

Solution

What I would do using an anonymous HASH reference :

#case 1, pass in hash
test({arg1 => 'test', arg2 => 'test2'});

#case 2, just pass in single values
test('test', 'test2');

sub test { 
    my $arg = shift;

    if(ref $arg eq 'HASH') { 
        ...;
    }
    #if values passed in as single values, do something else
    else { 
         ...;
    }
}

See
http://perldoc.perl.org/perlref.html
http://perldoc.perl.org/perlreftut.html

OTHER TIPS

The other answer is perfectly fine (and I've plusplussed it), but in the spirit of There's More That One Way To Do It™, and in the interest of pimping my own wares...

use v5.14;
use strict;
use warnings;
use Kavorka qw( multi fun );

# define a function with positional arguments
multi fun test (Str $arg1, Str $arg2) {
   say "positional";
   say "\$arg1 is $arg1";
   say "\$arg2 is $arg2";
}

# define a function with named arguments
multi fun test (Str :$arg1, Str :$arg2) {
   say "named";
   say "\$arg1 is $arg1";
   say "\$arg2 is $arg2";
}

# Call the function with positional arguments
test('foo', 'bar');

# Call the function with named arguments
test(arg1 => 'foo', arg2 => 'bar');

# Call the function with named arguments again
test({ arg1 => 'foo', arg2 => 'bar' });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top