Aion-Format

 view release on metacpan or  search on metacpan

README.md  view on Meta::CPAN

```perl
xxS  # -> 255
```

## to_str (;$scalar)

Преобразование в строку Perl без интерполяции.

```perl
to_str "a'\n" # => 'a\\'\n'
[map to_str, "a'\n"] # --> ["'a\\'\n'"]
```

## from_str (;$one_quote_str)

Преобразование из строки Perl без интерполяции.

```perl
from_str "'a\\'\n'"  # => a'\n
[map from_str, "'a\\'\n'"]  # --> ["a'\n"]
```

# SUBROUTINES/METHODS

# AUTHOR

Yaroslav O. Kosmina <dart@cpan.org>

# LICENSE

lib/Aion/Format.md  view on Meta::CPAN

```perl
xxS  # -> 255
```

## to_str (;$scalar)

Преобразование в строку Perl без интерполяции.

```perl
to_str "a'\n" # => 'a\\'\n'
[map to_str, "a'\n"] # --> ["'a\\'\n'"]
```

## from_str (;$one_quote_str)

Преобразование из строки Perl без интерполяции.

```perl
from_str "'a\\'\n'"  # => a'\n
[map from_str, "'a\\'\n'"]  # --> ["a'\n"]
```

# SUBROUTINES/METHODS

# AUTHOR

Yaroslav O. Kosmina <dart@cpan.org>

# LICENSE

lib/Aion/Format.pm  view on Meta::CPAN

#@category Преобразования

# Проводит соответствия
#
# replace "...", qr/.../ => sub {...}, ...
#
sub matches($@) { goto &replace }
sub replace($@) {
	my $s = shift;
	my $i = 0;
	my $re = join "\n| ", map { $i++ % 2 == 0? "(?<I$i> $_ )": () } @_;
	my $arg = \@_;
	my $fn = sub {
		for my $k (keys %+) {
			return $arg->[$k]->() if do { $k =~ /^I(\d+)\z/ and $k = $1 }
		}
	};

	$s =~ s/$re/$fn->()/gex;

	$s

lib/Aion/Format.pm  view on Meta::CPAN

sub from_str(;$) {
	my ($s) = @_ == 0? $_: @_;
	$s =~ s/^'(.*)'\z/$1/s;
	$s =~ s/\\([\\'])/$1/g;
	$s
}

# Упрощённый язык регулярок
sub nous($) {
	my ($templates) = @_;
	my $x = join "|", map {
		replace $_,
		# Срезаем все пробелы с конца:
		qr!\s*$! => sub {},
		# Срезаем все начальные строки:
		qr!^([ \t]*\n)*! => sub {},
		# С начала каждой строки 4 пробела или 0-3 пробела и табуляция:
		qr!^( {4}| {0,3}\t)!m => sub {},
		# Пробелы в конце строки и пробельные строки затем заменяем на \s*
		qr!([ \t]*\n)+! => sub { "\\s*" },
		# Заменяем все переменные {{}}:

lib/Aion/Format.pm  view on Meta::CPAN

		}
	}

	$s //= "N";
	$s =~ s/ \z//;
	$s
}

# Использованы символы из кодировки cp1251, что нужно для корректной записи в таблицы
our $CIF = join "", "0".."9", "A".."Z", "a".."z", "_-", # 64 символа для 64-ричной системы счисления
	(map chr, ord "А" .. ord "Я"), "ЁЂЃЉЊЌЋЏЎЈҐЄЇІЅ",
	(map chr, ord "а" .. ord "я"), "ёђѓљњќћџўјґєїіѕ",
	"‚„…†‡€‰‹‘’“”•–—™›¤¦§©«¬­®°±µ¶·№»",	do { no utf8; chr 0xa0 }, # небуквенные символы из cp1251
	"!\"#\$%&'()*+,./:;<=>?\@[\\]^`{|}~", # символы пунктуации ASCII
	" ", # пробел
	(map chr, 0 .. 0x1F, 0x7F), # управляющие символы ASCII
	# символ 152 (0x98) в cp1251 отсутствует.
;
# Переводит натуральное число в заданную систему счисления
sub to_radix($;$) {
	use bigint;
	my ($n, $radix) = @_;
	$radix //= 64;
	die "to_radix: The number system $radix is too large. Use NS before " . (1 + length $CIF) if $radix > length $CIF;
	$n+=0; $radix+=0;
	my $x = "";

lib/Aion/Format.pm  view on Meta::CPAN

Maximum length of TinyText mysql and mariadb data.
S - small.

	xxS  # -> 255

=head2 to_str (;$scalar)

Convert to Perl string without interpolation.

	to_str "a'\n" # => 'a\\'\n'
	[map to_str, "a'\n"] # --> ["'a\\'\n'"]

=head2 from_str (;$one_quote_str)

Conversion from Perl string without interpolation.

	from_str "'a\\'\n'"  # => a'\n
	[map from_str, "'a\\'\n'"]  # --> ["a'\n"]

=head1 SUBROUTINES/METHODS

=head1 AUTHOR

Yaroslav O. Kosmina L<mailto:dart@cpan.org>

=head1 LICENSE

âš– B<GPLv3>

lib/Aion/Format/Html.pm  view on Meta::CPAN

# ♠	«пики» (карточная масть)	&spades;	&#9824;
spades => 9824,
# ♣	«трефы» (карточная масть)	&clubs;	&#9827;
clubs => 9827,
# ♥	«червы» (карточная масть)	&hearts;	&#9829;
hearts => 9829,
# ♦	«бубны» (карточная масть)	&diams;	&#9830;
diams => 9830,
);

sub _set(@) { +{ map { $_ => 1 } @_ } }

# Теги не имеющие закрывающего тега
our %SINGLE_TAG = %{ _set qw/area base br col embed hr img input link meta param source track wbr/ };

# <li> закрывается, если приходит </ol> или </ul>
our %TOP_CLOSE_TAG = (
	li 			=> _set(qw/ol ul/),
	caption 	=> _set(qw/table/),
	thead 		=> _set(qw/table/),
	tbody 		=> _set(qw/table/),

lib/Aion/Format/Html.pm  view on Meta::CPAN

	my @page;		# массив элементов текста и тегов текущей страницы
	my $c = 0;		# количество символов в текущей странице
	my $i_page = 0;	# индекс элемента @page который привысил размер страницы
	my $c_page = 0;	# количество символов @page по $i_page
	my $is_proposal = 0;			# В конце текущей страницы обнаружен конец предложения
	my $re_proposal = qr/[.?!…]/;
	my @S;			# массив открывающих тегов [tag, '<tag ...>']

	# Функция фиксирует страницу и сбрасывает счётчики
	my $make_page = sub {
		push @pages, join "", @page, map { "</$_->[0]>" } reverse @S;
		$i_page = $c = $is_proposal = 0;
		@page = map $_->[1], @S;
	};
	
	for(grep length, split m{(
		<[a-z] [^<>]* >
		| </ \s* [a-z]\w* \s* >
		| &(?: [a-z]\w* | \# \d+ | \#x[0-9a-f]+ ) ;?
		| \n 		# Абзац
		| $re_proposal+	# Предложение
		| \b		# Слово
	)}xiu, $html) {

lib/Aion/Format/Html.pm  view on Meta::CPAN

	$_
}

# Все, кроме запрещённых:
#  applet, script, style, embed, object, param,
#  video, audio, source, track, frame, frameset, iframe, comment
#  html, head, body, title, meta, base, basefont, bgsound, link
#  form, keygen, output, textarea, select, option, optgroup, legend, label, input
#  plaintext, xmp
# А так же удаляет атрибуты начинающиеся на "on", name, for, formaction и др..
my %SAFE_TAG = map {$_=>1} qw/
a
abbr
acronym
address

area
article
aside

b

lib/Aion/Format/Html.pm  view on Meta::CPAN


ins
isindex

kbd
keygen

li

main
map
marquee
mark
menu

meter

nav
nobr
noembed
noframes

lib/Aion/Format/Html.pm  view on Meta::CPAN

tt

u
ul

var

wbr
/;

my %SAFE_ATTR = map {$_=>1} qw/
pubdate datetime
open optimum

dir lang language style tabindex title high low hreflang icon

max min

href media ping rel rev name type

class

lib/Aion/Format/Json.md  view on Meta::CPAN

to_json # -> $result
```

## from_json (;$string)

Разбирает строку в формате JSON в структуру Perl.

```perl
from_json '{"a": 10}' # --> {a => 10}

[map from_json, "{}", "2"]  # --> [{}, 2]
```

# AUTHOR

Yaroslav O. Kosmina <darviarush@mail.ru>

# LICENSE

âš– **GPLv3**

lib/Aion/Format/Json.pm  view on Meta::CPAN

	
	local $_ = $data;
	to_json # -> $result

=head2 from_json (;$string)

Parses a JSON string into a Perl structure.

	from_json '{"a": 10}' # --> {a => 10}
	
	[map from_json, "{}", "2"]  # --> [{}, 2]

=head1 AUTHOR

Yaroslav O. Kosmina L<mailto:darviarush@mail.ru>

=head1 LICENSE

âš– B<GPLv3>

=head1 COPYRIGHT

lib/Aion/Format/Url.md  view on Meta::CPAN


# SUBROUTINES

## to_url_param (;$scalar)

Экранирует `$scalar` для части поиска URL.

```perl
to_url_param "a b" # => a+b

[map to_url_param, "a b", "🦁"] # --> [qw/a+b %F0%9F%A6%81/]
```

## to_url_params (;$hash_ref)

Генерирует поисковую часть URL-адреса.

```perl
local $_ = {a => 1, b => [[1,2],3,{x=>10}]};
to_url_params  # => a&b[][]&b[][1]=2&b[1]=3&b[2][x]=10
```

lib/Aion/Format/Url.pm  view on Meta::CPAN

	my ($param) = @_ == 0? $_: @_;

	my @R;
	my @S = [$param];
	while(@S) {
		my $u = pop @S;
		my ($x, $key) = @$u;
		
		if(ref $x eq "HASH") {
			push @S, defined($key)
				? (map [$x->{$_}, "$key\[${\to_url_param}]"], sort keys %$x)
				: (map [$x->{$_}, to_url_param], sort keys %$x)
			;
		}
		elsif(ref $x eq "ARRAY") {
			my $i = '';
			push @S, map [$_, "$key\[${\($i++)}]"], @$x;
		}
		elsif(!defined $x) {}
		elsif($x eq 1) { unshift @R, $key }
		else {
			unshift @R, join "=", $key, to_url_param $x;
		}
	}
	
	join "&", @R
}

lib/Aion/Format/Url.pm  view on Meta::CPAN

Utilities for encoding and decoding URLs.

=head1 SUBROUTINES

=head2 to_url_param (;$scalar)

Escapes C<$scalar> for the search part of the URL.

	to_url_param "a b" # => a+b
	
	[map to_url_param, "a b", "🦁"] # --> [qw/a+b %F0%9F%A6%81/]

=head2 to_url_params (;$hash_ref)

Generates the search portion of the URL.

	local $_ = {a => 1, b => [[1,2],3,{x=>10}]};
	to_url_params  # => a&b[][]&b[][1]=2&b[1]=3&b[2][x]=10

=over

t/aion/format.t  view on Meta::CPAN

::done_testing; }; subtest 'xxS ()' => sub { 
local ($::_g0 = do {xxS}, $::_e0 = do {255}); ::ok defined($::_g0) == defined($::_e0) && $::_g0 eq $::_e0, 'xxS  # -> 255' or ::diag ::_struct_diff($::_g0, $::_e0); undef $::_g0; undef $::_e0;

# 
# ## to_str (;$scalar)
# 
# Преобразование в строку Perl без интерполяции.
# 
::done_testing; }; subtest 'to_str (;$scalar)' => sub { 
local ($::_g0 = do {to_str "a'\n"}, $::_e0 = "'a\\'\n'"); ::ok $::_g0 eq $::_e0, 'to_str "a\'\n" # => \'a\\\'\n\'' or ::diag ::_string_diff($::_g0, $::_e0); undef $::_g0; undef $::_e0;
local ($::_g0 = do {[map to_str, "a'\n"]}, $::_e0 = do {["'a\\'\n'"]}); ::is_deeply $::_g0, $::_e0, '[map to_str, "a\'\n"] # --> ["\'a\\\'\n\'"]' or ::diag ::_struct_diff($::_g0, $::_e0); undef $::_g0; undef $::_e0;

# 
# ## from_str (;$one_quote_str)
# 
# Преобразование из строки Perl без интерполяции.
# 
::done_testing; }; subtest 'from_str (;$one_quote_str)' => sub { 
local ($::_g0 = do {from_str "'a\\'\n'"}, $::_e0 = "a'\n"); ::ok $::_g0 eq $::_e0, 'from_str "\'a\\\'\n\'"  # => a\'\n' or ::diag ::_string_diff($::_g0, $::_e0); undef $::_g0; undef $::_e0;
local ($::_g0 = do {[map from_str, "'a\\'\n'"]}, $::_e0 = do {["a'\n"]}); ::is_deeply $::_g0, $::_e0, '[map from_str, "\'a\\\'\n\'"]  # --> ["a\'\n"]' or ::diag ::_struct_diff($::_g0, $::_e0); undef $::_g0; undef $::_e0;

# 
# # SUBROUTINES/METHODS
# 
# # AUTHOR
# 
# Yaroslav O. Kosmina <dart@cpan.org>
# 
# # LICENSE
# 

t/aion/format/json.t  view on Meta::CPAN

local ($::_g0 = do {to_json}, $::_e0 = do {$result}); ::ok defined($::_g0) == defined($::_e0) && $::_g0 eq $::_e0, 'to_json # -> $result' or ::diag ::_struct_diff($::_g0, $::_e0); undef $::_g0; undef $::_e0;

# 
# ## from_json (;$string)
# 
# Разбирает строку в формате JSON в структуру Perl.
# 
::done_testing; }; subtest 'from_json (;$string)' => sub { 
local ($::_g0 = do {from_json '{"a": 10}'}, $::_e0 = do {{a => 10}}); ::is_deeply $::_g0, $::_e0, 'from_json \'{"a": 10}\' # --> {a => 10}' or ::diag ::_struct_diff($::_g0, $::_e0); undef $::_g0; undef $::_e0;

local ($::_g0 = do {[map from_json, "{}", "2"]}, $::_e0 = do {[{}, 2]}); ::is_deeply $::_g0, $::_e0, '[map from_json, "{}", "2"]  # --> [{}, 2]' or ::diag ::_struct_diff($::_g0, $::_e0); undef $::_g0; undef $::_e0;

# 
# # AUTHOR
# 
# Yaroslav O. Kosmina <darviarush@mail.ru>
# 
# # LICENSE
# 
# âš– **GPLv3**
# 

t/aion/format/url.pm  view on Meta::CPAN

# 	my ($param) = @_ == 0? $_: @_;
# 
# 	my @R;
# 	my @S = [$param];
# 	while(@S) {
# 		my $u = pop @S;
# 		my ($x, $key) = @$u;
# 		
# 		if(ref $x eq "HASH") {
# 			push @S, defined($key)
# 				? (map [$x->{$_}, "$key\[${\to_url_param}]"], sort keys %$x)
# 				: (map [$x->{$_}, to_url_param], sort keys %$x)
# 			;
# 		}
# 		elsif(ref $x eq "ARRAY") {
# 			push @S, map [$_, "$key\[]"], @$x;
# 		}
# 		elsif(!defined $x) {}
# 		elsif($x eq 1) { unshift @R, $key }
# 		else {
# 			unshift @R, join "=", $key, to_url_param $x;
# 		}
# 	}
# 	
# 	join "&", @R
# }

t/aion/format/url.pm  view on Meta::CPAN

# Utilities for encoding and decoding URLs.
# 
# =head1 SUBROUTINES
# 
# =head2 to_url_param (;$scalar)
# 
# Escapes C<$scalar> for the search part of the URL.
# 
# 	to_url_param "a b" # => a+b
# 	
# 	[map to_url_param, "a b", "🦁"] # --> [qw/a+b %F0%9F%A6%81/]
# 
# =head2 to_url_params (;$hash_ref)
# 
# Generates the search portion of the URL.
# 
# 	local $_ = {a => 1, b => [[1,2],3,{x=>10}]};
# 	to_url_params  # => a&b[][]&b[][]=2&b[]=3&b[][x]=10
# 
# =over
# 

t/aion/format/url.t  view on Meta::CPAN

# 
# # SUBROUTINES
# 
# ## to_url_param (;$scalar)
# 
# Экранирует `$scalar` для части поиска URL.
# 
::done_testing; }; subtest 'to_url_param (;$scalar)' => sub { 
local ($::_g0 = do {to_url_param "a b"}, $::_e0 = "a+b"); ::ok $::_g0 eq $::_e0, 'to_url_param "a b" # => a+b' or ::diag ::_string_diff($::_g0, $::_e0); undef $::_g0; undef $::_e0;

local ($::_g0 = do {[map to_url_param, "a b", "🦁"]}, $::_e0 = do {[qw/a+b %F0%9F%A6%81/]}); ::is_deeply $::_g0, $::_e0, '[map to_url_param, "a b", "🦁"] # --> [qw/a+b %F0%9F%A6%81/]' or ::diag ::_struct_diff($::_g0, $::_e0); undef $::_g0; undef ...

# 
# ## to_url_params (;$hash_ref)
# 
# Генерирует поисковую часть URL-адреса.
# 
::done_testing; }; subtest 'to_url_params (;$hash_ref)' => sub { 
local $_ = {a => 1, b => [[1,2],3,{x=>10}]};
local ($::_g0 = do {to_url_params}, $::_e0 = "a&b[][]&b[][1]=2&b[1]=3&b[2][x]=10"); ::ok $::_g0 eq $::_e0, 'to_url_params  # => a&b[][]&b[][1]=2&b[1]=3&b[2][x]=10' or ::diag ::_string_diff($::_g0, $::_e0); undef $::_g0; undef $::_e0;



( run in 1.398 second using v1.01-cache-2.11-cpan-39bf76dae61 )