_hashify: verallgemeinert, getestet, nach SL::Util verschoben (und das dabei erfunden)
[kivitendo-erp.git] / SL / Util.pm
1 package SL::Util;
2
3 use strict;
4
5 use parent qw(Exporter);
6
7 use Carp;
8
9 our @EXPORT_OK = qw(_hashify);
10
11 sub _hashify {
12   my $keep = shift;
13
14   croak "Invalid number of entries to keep" if 0 > $keep;
15
16   return @_[0..scalar(@_) - 1] if $keep >= scalar(@_);
17   return ($keep ? @_[0..$keep - 1] : (),
18           ((1 + $keep) == scalar(@_)) && ((ref($_[$keep]) || '') eq 'HASH') ? %{ $_[$keep] } : @_[$keep..scalar(@_) - 1]);
19 }
20
21 1;
22 __END__
23
24 =pod
25
26 =encoding utf8
27
28 =head1 NAME
29
30 SL::Util - Assorted utility functions
31
32 =head1 OVERVIEW
33
34 Most important things first:
35
36 DO NOT USE C<@EXPORT> HERE! Only C<@EXPORT_OK> is allowed!
37
38 =head1 FUNCTIONS
39
40 =over 4
41
42 =item C<_hashify $num, @args>
43
44 Hashifies the very last argument. Returns a list consisting of two
45 parts:
46
47 The first part are the first C<$num> elements of C<@args>.
48
49 The second part depends on the remaining arguments. If exactly one
50 argument remains and is a hash reference then its dereferenced
51 elements will be used. Otherwise the remaining elements of C<@args>
52 will be returned as-is.
53
54 Useful if you want to write code that can be called from Perl code and
55 Template code both. Example:
56
57   use SL::Util qw(_hashify);
58
59   sub do_stuff {
60     my ($self, %params) = _hashify(1, @_);
61     # Now do stuff, obviously!
62   }
63
64 =back
65
66 =head1 BUGS
67
68 Nothing here yet.
69
70 =head1 AUTHOR
71
72 Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>
73
74 =cut