1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Perlでバイナリ文字列をunpackするときの改行の考慮は十分に

Posted at

Perl でバイナリ文字列を可読にするために、以下のような記述をすることは、わりとあると思います。(URLエンコードや暗号化(RC4等)の時)

$str =~ s/(.)/'%'.unpack('H2', $1)/eg;

($str =~ s/([^ ])/'%'.unpack('H2', $1)/eg; $str =~ tr/ /+/; のように . を使っていない場合は、関係ないです。)

しかし上記のように . の場合、$str に改行コードが含まれていた場合どうなるほうが良いかを考えておくほうが良いです。

上記の場合 . に改行コードはマッチしませんので、以下のようになります。

my $str = "123\n456";
$str =~ s/(.)/'%'.unpack('H2', $1)/eg;
print $str;
# (出力結果)
%31%32%33
%34%35%36

改行が改行のままで良いのであれば、問題ないのですが、この文字列をファイルに出力などの場合は、意図と違う動作になる場合もあります。このような場合は、以下のように s オプションを付けると回避できます。

$str =~ s/(.)/'%'.unpack('H2', $1)/egs;
my $str = "123\n456";
$str =~ s/(.)/'%'.unpack('H2', $1)/egs;
print $str;
# (出力結果)
%31%32%33%0a%34%35%36

バイナリ文字列内の改行コードの考慮は十分に。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?