Created
May 16, 2014 04:53
-
-
Save ayumu83s/95976cae164489767801 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use utf8; | |
use strict; | |
use warnings; | |
use Encode 'encode_utf8'; | |
# 文字が指定のバイト数を超えている場合に切り取る。 | |
sub kirisute_gomen { | |
my ($string, $byte_len, $str_len) = @_; | |
return $string if (length(encode_utf8($string)) <= $byte_len && length($string) <= $str_len); | |
# 指定の文字数まで切り取って、byte超えてたら1文字ずづ捨てていく作戦 | |
my $result = substr($string, 0, $str_len); | |
while (length(encode_utf8($result)) > $byte_len || length($result) > $str_len) { | |
$result = substr($result, 0, -1); | |
} | |
return $result; | |
} | |
=pod | |
# 5文字(10byte)制限のテスト | |
kirisute_gomen('あいうえお', 10, 5); # あいう 9byte | |
kirisute_gomen('あいueお', 10, 5); # あいue 8byte | |
=cut |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment