File Coverage

blib/lib/Sub/Params.pm
Criterion Covered Total %
statement 37 38 97.3
branch 9 12 75.0
condition 8 12 66.6
subroutine 7 7 100.0
pod 1 1 100.0
total 62 70 88.5


line stmt bran cond sub pod time code
1             # © 2017-2018 GoodData Corporation
2              
3 1     1   89946 use 5.006;
  1         4  
4 1     1   5 use strict;
  1         2  
  1         20  
5 1     1   5 use warnings;
  1         2  
  1         62  
6              
7             package Sub::Params;
8              
9             our $VERSION = '1.0.0';
10              
11 1     1   6 use parent 'Exporter';
  1         2  
  1         7  
12              
13 1     1   65 use Hash::Util qw[];
  1         2  
  1         19  
14 1     1   4 use Ref::Util qw[ is_plain_hashref ];
  1         2  
  1         263  
15              
16             our @EXPORT_OK = (
17             'named_or_positional_arguments'
18             );
19              
20             sub named_or_positional_arguments {
21 6     6 1 16233 my (%args) = @_;
22 6         10 my $args = $args{args};
23 6         7 my $names = $args{names};
24              
25 6 50       12 return unless $args;
26 6 100       12 return unless @$args;
27 5 100       11 return @$args unless @$names;
28              
29             # Use restricted hashes to detects how function was called
30 4         5 my %params;
31 4         9 Hash::Util::lock_keys %params, @$names;
32              
33 4         92 local $@;
34 4         8 local $SIG{__DIE__};
35              
36             # single argument, hashref => can be named argument hashref
37             return %params
38             if @$args == 1
39             and is_plain_hashref( $args->[0] )
40 4 50 66     16 and eval { %params = %{ $args->[0] }; 1 }
  1   66     2  
  1         2  
  1         7  
41             ;
42              
43             # with even number of argument => looks like named arguments
44             return %params
45             if @$args % 2 == 0
46 3 100 100     11 and eval { %params = @$args; 1 }
  2         13  
  1         7  
47             ;
48              
49             # with more arguments than names should be named arguments
50             return %params
51             if @$args <= @$names
52 2 50 33     8 and do { @params{@$names} = @$args; 1 }
  2         5  
  2         17  
53             ;
54              
55 0           return @$args;
56             }
57              
58             1;
59              
60             __END__