Aion-Format

 view release on metacpan or  search on metacpan

i18n/Aion/Format.ru-en.po  view on Meta::CPAN

msgstr "The constant is equal to one gibibyte."

msgid "Константа равна одному мебибайту."
msgstr "The constant is equal to one mebibyte."

msgid "Константа равна одному кибибайту."
msgstr "The constant is equal to one kibibyte."

msgid "Максимальная длина данных LongText mysql и mariadb.\n"
"L - large."
msgstr "Maximum length of LongText mysql and mariadb data.\n"
"L - large."

msgid "Максимальная длина данных MediumText mysql и mariadb.\n"
"M - medium."
msgstr "Maximum length of MediumText mysql and mariadb data.\n"
"M - medium."

msgid "Максимальная длина текста данных mysql и mariadb.\n"
"R - regularity."
msgstr "Maximum text length of mysql and mariadb data.\n"
"R - regularity."

msgid "Максимальная длина данных TinyText mysql и mariadb.\n"
"S - small."
msgstr "Maximum length of TinyText mysql and mariadb data.\n"
"S - small."

msgid "Преобразование в строку Perl без интерполяции."
msgstr "Convert to Perl string without interpolation."

msgid "Преобразование из строки Perl без интерполяции."
msgstr "Conversion from Perl string without interpolation."

msgid "âš– **GPLv3**"
msgstr "âš– **GPLv3**"

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

	"!\"#\$%&'()*+,./:;<=>?\@[\\]^`{|}~", # символы пунктуации 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 = "";
	for(;;) {
		my $cif_idx = $n % $radix;
		my $cif = substr $CIF, $cif_idx, 1;
		$x =~ s/^/$cif/;
		last unless $n = int($n / $radix);
	}
	return $x;
}

# Парсит натуральное число в указанной системе счисления
sub from_radix(@) {
	use bigint;
	my ($s, $radix) = @_;
	$radix //= 64;
	$radix+=0;
	die "from_radix: The number system $radix is too large. Use NS before " . (1 + length $CIF) if $radix > length $CIF;
	my $x = 0;
	for my $ch (split "", $s) {
		$x = $x*$radix + index $CIF, $ch;
	}
	return $x;
}

# Округляет до указанного разряда числа
sub round($;$) {
	my ($x, $dec) = @_;

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


	return num(round($n)) . "b";
}

# Оставляет $n цифр до и после точки: 10.11 = 10, 0.00012 = 0.00012, 1.2345 = 1.2, если $n = 2
sub sround($;$) {
	my ($number, $digits) = @_;
	$digits //= 2;
	my $num = sprintf("%.100f", $number);
	$num =~ /^-?0?(\d*)\.(0*)[1-9]/;
	return "" . round($num, $digits + length $2) if length($1) == 0;
	my $k = $digits - length $1;
	return "" . round($num, $k < 0? 0: $k);
}

# Кибибайт
sub KiB() { 2**10 }

# Мебибайт
sub MiB() { 2**20 }

# Гибибайт

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

	MiB  # -> 2**20

=head2 KiB ()

The constant is equal to one kibibyte.

	KiB  # -> 2**10

=head2 xxL ()

Maximum length of LongText mysql and mariadb data.
L - large.

	xxL  # -> 4*GiB-1

=head2 xxM ()

Maximum length of MediumText mysql and mariadb data.
M - medium.

	xxM  # -> 16*MiB-1

=head2 xxR ()

Maximum text length of mysql and mariadb data.
R - regularity.

	xxR  # -> 64*KiB-1

=head2 xxS ()

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'"]

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

	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) {

		if(/^&/) {$c++} 	# html-символ
		elsif(/^<\/\s*([a-z]\w*)/) { # закрывающий тег
			my $tag = lc $1;
			eval { out_tag @S, $tag };
			next if $@;
			# </p> превращаем в <p></p>
			$_ = "<p></p>" if $tag eq "p";
		}
		elsif(/^<([a-z]\w*)/) { in_tag @S, lc $1, $_ }	# тег
		else {$c += length}	# текст

		push @page, $_; # накапливаем символы в массиве @page

		next if $c < $symbols_on_page;	# страницу не набрали - тогда на next

		$c_page = $c, $i_page = @page if !$i_page;

		# Просматриваем вперёд пока не найдём границу или не достигнем ограничения
		if(/^\n/) { $make_page->() } 	# Абзац
		elsif(!$is_proposal && /^$re_proposal/) { $i_page = @page; $c_page = $c; $is_proposal = 1 }
		elsif($c >= $max) {
			# Если следующий за предложением или словом элемент - пробелы, то добавляем их к странице
			$c_page -= length $page[$i_page++] if $page[$i_page] =~ /^\s/;
			my @x = splice @page, $i_page;
			$make_page->();
			push @page, @x;
			$c -= $c_page;
		}
	}

	$make_page->() if @page;

	# Если размер последней страницы меньше чем 2/3, то добавляем её к предпоследней
	$pages[$#pages - 1] .= pop @pages if @pages > 1 and length($pages[$#pages]) < $symbols_on_page * 2 / 3;

	#my $len = 0; $len += length for @pages;
	#die "Суммарный размер страниц не изменился: " . length($html) . " == $len pages=" . @pages . " ->\n\n$html" if $len == length $html;

	my ($end1) = $html =~ m!([^<>\s]{1,13})\s*(</?\w[^<>]*>\s*)*$!a;
	my ($end2) = $pages[$#pages] =~ m!([^<>\s]{1,13})\s*(</?\w[^<>]*>\s*)*$!a;
	die "Концы текста и последней страницы не сходятся! `$end1` <> `$end2`" if $end1 ne $end2;

	return @pages;
}

our %TAG2SPACE = (
	"br" => "\n",

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

	
	join "&", @R
}

# Определяет кодировку. В koi8-r и в cp1251 большие и малые буквы как бы поменялись местами, поэтому у правильной кодировки вес будет больше
sub _bohemy {
	my ($s) = @_;
	my $c = 0;
	while($s =~ /[а-яё]+/gi) {
		my $x = $&;
		if($x =~ /^[А-ЯЁа-яё][а-яё]*$/) { $c += length $x } else { $c -= length $x }
	}
	$c
}

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

	utf8::encode($param) if utf8::is_utf8($param);

	{

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

		$link{path} = "/";
	} else { delete $link{path} }

	$link{orig} = $orig;
	$link{onpage} = $onpage;
	$link{link} = join "", $link{proto}, "://",
		exists $link{user} || exists $link{pass}? ($link{user},
			exists $link{pass}? ":$link{pass}": (), '@'): (),
		$link{dom},
		$link{path},
		length($link{query})? ("?", $link{query}): (),
		length($link{hash})? ("#", $link{hash}): (),
	;

	return \%link;
}

# Нормализует url
sub normalize_url($;$$) {
	parse_url($_[0], $_[1], $_[2])->{link}
}

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

use common::sense; use open qw/:std :utf8/;  use Carp qw//; use Cwd qw//; use File::Basename qw//; use File::Find qw//; use File::Slurper qw//; use File::Spec qw//; use File::Path qw//; use Scalar::Util qw//;  use Test::More 0.98;  use String::Diff q...
# # NAME
# 
# Aion::Format - расширение Perl для форматирования чисел, раскрашивания вывода и т.п.
# 
# # VERSION
# 
# 0.1.1
# 
# # SYNOPSIS
# 

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

use common::sense; use open qw/:std :utf8/;  use Carp qw//; use Cwd qw//; use File::Basename qw//; use File::Find qw//; use File::Slurper qw//; use File::Spec qw//; use File::Path qw//; use Scalar::Util qw//;  use Test::More 0.98;  use String::Diff q...
# # NAME
# 
# Aion::Format::Html - библиотека для форматирования HTML
# 
# # SYNOPSIS
# 
subtest 'SYNOPSIS' => sub { 
use Aion::Format::Html;

local ($::_g0 = do {from_html "<b>&excl;</b>"}, $::_e0 = "!"); ::ok $::_g0 eq $::_e0, 'from_html "<b>&excl;</b>" # => !' or ::diag ::_string_diff($::_g0, $::_e0); undef $::_g0; undef $::_e0;

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

use common::sense; use open qw/:std :utf8/;  use Carp qw//; use Cwd qw//; use File::Basename qw//; use File::Find qw//; use File::Slurper qw//; use File::Spec qw//; use File::Path qw//; use Scalar::Util qw//;  use Test::More 0.98;  use String::Diff q...
# # NAME
# 
# Aion::Format::Json - расширение Perl для форматирования JSON
# 
# # SYNOPSIS
# 
subtest 'SYNOPSIS' => sub { 
use Aion::Format::Json;

local ($::_g0 = do {to_json {a => 10}}, $::_e0 = "{\n   \"a\": 10\n}\n"); ::ok $::_g0 eq $::_e0, 'to_json {a => 10}    # => {\n   "a": 10\n}\n' or ::diag ::_string_diff($::_g0, $::_e0); undef $::_g0; undef $::_e0;

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

use common::sense; use open qw/:std :utf8/;  use Carp qw//; use Cwd qw//; use File::Basename qw//; use File::Find qw//; use File::Slurper qw//; use File::Spec qw//; use File::Path qw//; use Scalar::Util qw//;  use Test::More 0.98;  use String::Diff q...
# 
# use common::sense;
# 
# use List::Util qw//;
# use Encode qw//;
# 
# use Exporter qw/import/;
# our @EXPORT = our @EXPORT_OK = grep {
# 	ref \$Aion::Format::Url::{$_} eq "GLOB"
# 		&& *{$Aion::Format::Url::{$_}}{CODE} && !/^(_|(NaN|import)\z)/n

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

# 	
# 	join "&", @R
# }
# 
# # Определяет кодировку. В koi8-r и в cp1251 большие и малые буквы как бы поменялись местами, поэтому у правильной кодировки вес будет больше
# sub _bohemy {
# 	my ($s) = @_;
# 	my $c = 0;
# 	while($s =~ /[а-яё]+/gi) {
# 		my $x = $&;
# 		if($x =~ /^[А-ЯЁа-яё][а-яё]*$/) { $c += length $x } else { $c -= length $x }
# 	}
# 	$c
# }
# 
# sub from_url_param(;$) {
# 	my ($param) = @_ == 0? $_: @_;
# 
# 	utf8::encode($param) if utf8::is_utf8($param);
# 
# 	{

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

# 		$link{path} = "/";
# 	} else { delete $link{path} }
# 
# 	$link{orig} = $orig;
# 	$link{onpage} = $onpage;
# 	$link{link} = join "", $link{proto}, "://",
# 		exists $link{user} || exists $link{pass}? ($link{user},
# 			exists $link{pass}? ":$link{pass}": (), '@'): (),
# 		$link{dom},
# 		$link{path},
# 		length($link{query})? ("?", $link{query}): (),
# 		length($link{hash})? ("#", $link{hash}): (),
# 	;
# 
# 	return \%link;
# }
# 
# # Нормализует url
# sub normalize_url($;$$) {
# 	parse_url($_[0], $_[1], $_[2])->{link}
# }
# 

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

use common::sense; use open qw/:std :utf8/;  use Carp qw//; use Cwd qw//; use File::Basename qw//; use File::Find qw//; use File::Slurper qw//; use File::Spec qw//; use File::Path qw//; use Scalar::Util qw//;  use Test::More 0.98;  use String::Diff q...
# # NAME
# 
# Aion::Format::Url - утилиты для кодирования и декодирования URL-адресов
# 
# # SYNOPSIS
# 
subtest 'SYNOPSIS' => sub { 
use Aion::Format::Url;

local ($::_g0 = do {to_url_params {a => 1, b => [[1,2],3,{x=>10}]}}, $::_e0 = "a&b[][]&b[][1]=2&b[1]=3&b[2][x]=10"); ::ok $::_g0 eq $::_e0, 'to_url_params {a => 1, b => [[1,2],3,{x=>10}]} # => a&b[][]&b[][1]=2&b[1]=3&b[2][x]=10' or ::diag ::_string_d...

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

use common::sense; use open qw/:std :utf8/;  use Carp qw//; use Cwd qw//; use File::Basename qw//; use File::Find qw//; use File::Slurper qw//; use File::Spec qw//; use File::Path qw//; use Scalar::Util qw//;  use Test::More 0.98;  use String::Diff q...
# # NAME
# 
# Aion::Format::Yaml - конвертер из/в yaml
# 
# # SYNOPSIS
# 
subtest 'SYNOPSIS' => sub { 
use Aion::Format::Yaml qw/from_yaml to_yaml/;

local ($::_g0 = do {to_yaml {foo => 'bar'}}, $::_e0 = do {"foo: bar\n"}); ::ok defined($::_g0) == defined($::_e0) && $::_g0 eq $::_e0, 'to_yaml {foo => \'bar\'} # -> "foo: bar\n"' or ::diag ::_struct_diff($::_g0, $::_e0); undef $::_g0; undef $::_e0;



( run in 0.796 second using v1.01-cache-2.11-cpan-75ffa21a3d4 )