epic-s6ts
[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 trim);
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 sub trim {
35   my $value = shift;
36   $value    =~ s{^ \p{WSpace}+ }{}xg if defined($value);
37   $value    =~ s{ \p{WSpace}+ $}{}xg if defined($value);
38   return $value;
39 }
40
41 1;
42 __END__
43
44 =pod
45
46 =encoding utf8
47
48 =head1 NAME
49
50 SL::Util - Assorted utility functions
51
52 =head1 OVERVIEW
53
54 Most important things first:
55
56 DO NOT USE C<@EXPORT> HERE! Only C<@EXPORT_OK> is allowed!
57
58 =head1 FUNCTIONS
59
60 =over 4
61
62 =item C<_hashify $num, @args>
63
64 Hashifies the very last argument. Returns a list consisting of two
65 parts:
66
67 The first part are the first C<$num> elements of C<@args>.
68
69 The second part depends on the remaining arguments. If exactly one
70 argument remains and is a hash reference then its dereferenced
71 elements will be used. Otherwise the remaining elements of C<@args>
72 will be returned as-is.
73
74 Useful if you want to write code that can be called from Perl code and
75 Template code both. Example:
76
77   use SL::Util qw(_hashify);
78
79   sub do_stuff {
80     my ($self, %params) = _hashify(1, @_);
81     # Now do stuff, obviously!
82   }
83
84 =item C<camilify $string>
85
86 Returns C<$string> converted from underscore-style to
87 camel-case-style, e.g. for the string C<stupid_example_dude> it will
88 return C<StupidExampleDude>.
89
90 L</snakify> does the reverse.
91
92 =item C<snakify $string>
93
94 Returns C<$string> converted from camel-case-style to
95 underscore-style, e.g. for the string C<EvenWorseExample> it will
96 return C<even_worse_example>.
97
98 L</camilify> does the reverse.
99
100 =item C<trim $string>
101
102 Removes all leading and trailing whitespaces from C<$string> and
103 returns it. Whitespaces within the string won't be changed.
104
105 This function considers everything matching the Unicode character
106 property "Whitespace" (C<WSpace>) to be a whitespace.
107
108 =back
109
110 =head1 BUGS
111
112 Nothing here yet.
113
114 =head1 AUTHOR
115
116 Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>
117
118 =cut