perl で文字列から1文字ずつ取得して配列に格納するには、以下のように split 関数を使うのが楽。
splitString.pl
use strict; use warnings; use Encode; my $inputStr = shift; my $decodedInputStr = decode('Shift_JIS', $inputStr); # SJISの文字列から内部文字列に変換 my @chars = getCharsArray($decodedInputStr); foreach my $char (@chars) { my $encodedChar = encode('Shift_JIS', $char); # 内部文字からSJISの文字に変換 print "$encodedChar\n"; } sub getCharsArray { my $str = shift; my @chars = split(//, $str); # ★ここ! return @chars; }
上記のスクリプトを、
splitString.pl abcあいう
として実行すると、一文字ずつ分けられて、
a
b
c
あ
い
う
と出力される。
なお、上記のスクリプトは SJIS 環境で実行したので、SJIS の文字列から内部文字列(≒UTF-8)にデコードする処理と、内部文字からSJISの文字にエンコードする処理が入っている。(マルチバイト文字対策)