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