From 98c23539610c6d083265454858ef25e563f74b21 Mon Sep 17 00:00:00 2001 From: Moritz Bunkus Date: Fri, 1 Apr 2016 16:41:49 +0200 Subject: [PATCH] =?utf8?q?trim-Funktion=20zum=20Entfernen=20f=C3=BChrender?= =?utf8?q?=20und=20anh=C3=A4ngender=20Whitespaces?= MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit --- SL/Util.pm | 16 +++++++++++++++- t/helper/trim.t | 20 ++++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 t/helper/trim.t diff --git a/SL/Util.pm b/SL/Util.pm index 2fdd9c1f6..9022d939b 100644 --- a/SL/Util.pm +++ b/SL/Util.pm @@ -6,7 +6,7 @@ use parent qw(Exporter); use Carp; -our @EXPORT_OK = qw(_hashify camelify snakify); +our @EXPORT_OK = qw(_hashify camelify snakify trim); sub _hashify { my $keep = shift; @@ -31,6 +31,12 @@ sub snakify { lc $str; } +sub trim { + my $value = shift; + $value =~ s{^ \p{WSpace}+ | \p{WSpace}+ $}{}xg if defined($value); + return $value; +} + 1; __END__ @@ -90,6 +96,14 @@ return C. L does the reverse. +=item C + +Removes all leading and trailing whitespaces from C<$string> and +returns it. Whitespaces within the string won't be changed. + +This function considers everything matching the Unicode character +property "Whitespace" (C) to be a whitespace. + =back =head1 BUGS diff --git a/t/helper/trim.t b/t/helper/trim.t new file mode 100644 index 000000000..52b0c8d24 --- /dev/null +++ b/t/helper/trim.t @@ -0,0 +1,20 @@ +use Test::More tests => 11; + +use strict; +use utf8; + +use lib 't'; + +use SL::Util qw(trim); + +is(trim("hello"), "hello", "hello"); +is(trim("hello "), "hello", "hello "); +is(trim(" hello"), "hello", " hello"); +is(trim(" hello "), "hello", " hello "); +is(trim(" h el lo "), "h el lo", " h el lo "); +is(trim("\n\t\rh\nello"), "h\nello", "line feed, horizontal tab, carriage return; line feed within word"); +is(trim("\x{a0}h\nello"), "h\nello", "non-breaking space"); +is(trim("h\nello\n\t\r"), "h\nello", "line feed, horizontal tab, carriage return; line feed within word"); +is(trim("h\nello\x{a0}"), "h\nello", "non-breaking space"); +is(trim("h\ne\x{a0}llo\x{a0}"), "h\ne\x{a0}llo", "non-breaking space within word"); +is(trim(undef), undef, "undef"); -- 2.20.1