2fdd9c1f61d78089f9661735f1083f79216a6736
[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 camelify snakify);
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 sub camelify {
22   my ($str) = @_;
23   $str =~ s/_+([[:lower:]])/uc($1)/ge;
24   ucfirst $str;
25 }
26
27 sub snakify {
28   my ($str) = @_;
29   $str =~ s/_([[:upper:]])/'_' . lc($1)/ge;
30   $str =~ s/(?<!^)([[:upper:]])/'_' . lc($1)/ge;
31   lc $str;
32 }
33
34 1;
35 __END__
36
37 =pod
38
39 =encoding utf8
40
41 =head1 NAME
42
43 SL::Util - Assorted utility functions
44
45 =head1 OVERVIEW
46
47 Most important things first:
48
49 DO NOT USE C<@EXPORT> HERE! Only C<@EXPORT_OK> is allowed!
50
51 =head1 FUNCTIONS
52
53 =over 4
54
55 =item C<_hashify $num, @args>
56
57 Hashifies the very last argument. Returns a list consisting of two
58 parts:
59
60 The first part are the first C<$num> elements of C<@args>.
61
62 The second part depends on the remaining arguments. If exactly one
63 argument remains and is a hash reference then its dereferenced
64 elements will be used. Otherwise the remaining elements of C<@args>
65 will be returned as-is.
66
67 Useful if you want to write code that can be called from Perl code and
68 Template code both. Example:
69
70   use SL::Util qw(_hashify);
71
72   sub do_stuff {
73     my ($self, %params) = _hashify(1, @_);
74     # Now do stuff, obviously!
75   }
76
77 =item C<camilify $string>
78
79 Returns C<$string> converted from underscore-style to
80 camel-case-style, e.g. for the string C<stupid_example_dude> it will
81 return C<StupidExampleDude>.
82
83 L</snakify> does the reverse.
84
85 =item C<snakify $string>
86
87 Returns C<$string> converted from camel-case-style to
88 underscore-style, e.g. for the string C<EvenWorseExample> it will
89 return C<even_worse_example>.
90
91 L</camilify> does the reverse.
92
93 =back
94
95 =head1 BUGS
96
97 Nothing here yet.
98
99 =head1 AUTHOR
100
101 Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>
102
103 =cut