Permalink
Browse files

Tidy up Text::Escape a bit, fix some rough edges

(but not all)
  • Loading branch information...
flussence committed Aug 11, 2011
1 parent 4c5be46 commit 60c1016391ffa7786a9ac43478857c7ee7bc8099
Showing with 18 additions and 15 deletions.
  1. +18 −15 lib/Text/Escape.pm
View
@@ -2,19 +2,21 @@ use v6;
module Text::Escape;
sub escape($str, $how) is export {
- my $m = $how.lc;
- return $str if $m eq 'none';
- return escape_str($str, &escape_html_char) if $m eq 'html';
- return escape_str($str, &escape_uri_char ) if $m eq 'url' | 'uri';
- die "Don't know how to escape format '$how' yet";
+ given $how.lc {
+ when 'none' { $str }
+ when 'html' { escape_str($str, &escape_html_char) }
+ when 'uri' | 'url' { escape_str($str, &escape_uri_char) }
+ default { fail "Don't know how to escape format $how yet" }
+ }
}
sub escape_html_char($c) {
my %escapes = (
- '<' => '&lt;',
- '>' => '&gt;',
- '&' => '&amp;',
- '"' => '&quot;',
+ q{<} => '&lt;',
+ q{>} => '&gt;',
+ q{&} => '&amp;',
+ q{"} => '&quot;',
+ q{'} => '&#39;',
);
%escapes{$c} // $c;
}
@@ -23,17 +25,18 @@ sub escape_uri_char($c) {
my $allowed = 'abcdefghijklmnopqrstuvwxyz'
~ 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
~ '0123456789'
- ~ '-_.!~*\'()';
+ ~ q{-_.!~*'()};
+
return $c if defined $allowed.index($c);
- # I do not fully assured with thats '+' here,
- # mb that is not fully correct put it always on both side
- return sprintf('+%%%x+', ord($c));
+
+ # TODO: each char should be UTF-8 encoded, then its bytes %-encoded
+ return q{%} ~ ord($c).fmt('%x');
}
sub escape_str($str, $callback) {
my $result = '';
- for 0 .. ($str.chars -1 ) -> $index {
- $result ~= $callback( $str.substr: $index, 1 );
+ for ^$str.chars -> $index {
+ $result ~= $callback($str.substr: $index, 1)
}
return $result;
}

0 comments on commit 60c1016

Please sign in to comment.