Perl でバイト数を制限しつつ、文字列を妥当なバイト列に変換したい
use strict;
use warnings;
use utf8;
use Encode;
sub encode_with_limit {
my ($encoding, $str, $limit) = @_;
$encoding = Encode::find_encoding($encoding);
my $encoded = '';
for (my $i = 0; $i < length($str); $i++) {
my $chr = $encoding->encode(substr($str, $i, 1));
if (length($encoded . $chr) > $limit) {
last;
} else {
$encoded .= $chr;
}
}
$encoded;
}
use Test::More;
is encode_with_limit('UTF-8', 'あいうえお', 1), encode_utf8('');
is encode_with_limit('UTF-8', 'あいうえお', 2), encode_utf8('');
is encode_with_limit('UTF-8', 'あいうえお', 3), encode_utf8('あ');
is encode_with_limit('UTF-8', 'あいうえお', 4), encode_utf8('あ');
is encode_with_limit('UTF-8', 'あいうえお', 5), encode_utf8('あ');
is encode_with_limit('UTF-8', 'あいうえお', 6), encode_utf8('あい');
is encode_with_limit('UTF-8', 'あいうえお', 9), encode_utf8('あいう');
done_testing; こうしたんだけど、もっと簡単にできないんだろうか…
#!/usr/bin/env perl
use strict;
use warnings;
use utf8;
use Encode;
sub encode_with_limit {
my ($encoding, $str, $limit) = @_;
$encoding = Encode::find_encoding($encoding);
my $encoded = $encoding->encode($str);
my $short = $encoding->decode(substr($encoded, 0, $limit), Encode::FB_QUIET);
$encoding->encode($short);
}
use Test::More;
is encode_with_limit('UTF-8', 'あいうえお', 1), encode_utf8('');
is encode_with_limit('UTF-8', 'あいうえお', 2), encode_utf8('');
is encode_with_limit('UTF-8', 'あいうえお', 3), encode_utf8('あ');
is encode_with_limit('UTF-8', 'あいうえお', 4), encode_utf8('あ');
is encode_with_limit('UTF-8', 'あいうえお', 5), encode_utf8('あ');
is encode_with_limit('UTF-8', 'あいうえお', 6), encode_utf8('あい');
is encode_with_limit('UTF-8', 'あいうえお', 9), encode_utf8('あいう');
done_testing; もっと簡単に書けたけど、効率は悪そう。
関連エントリー
- リクエストオブジェクトへ、型を明示するメソッドの追加 ウェブアプリケーションを書くとき、最近はだいたい Plack::Request なりなんなりを継承して、そのプロジェクト専用のリクエスト/レ...
- Slack に Tiarra から接続する (SSL) Slack 側の設定 チームアドミンの Gateways で Enable IRC gateway してもらう Tiarra 側の設定 pl...
- SQLite の WITHOUT ROWID の効果測定 SQLite で「PRIMARY KEY」を《真のプライマリキー》とするには | tech - 氾濫原 の続きです。 以下のような簡単なベン...
- Google Fit の REST API で体重を自動入力する (画像は過去に入力したデータを全て Google Fit へ入力しなおした様子) Fit API 全体の概念 単純にグローバルな「体重」に対...
- perl 5.19.9 の signatures 構文 (普通に引数を書ける構文) を試す Perl 5.19.9 で実装された signatures の構文をためしてみる - tokuhirom blog を見てそんなのできたのか...