请允许我发表一个关于将字符串视为二进制数组的小例子 - 因为我自己发现很难相信所谓的“substr”会处理空字节;但似乎它 - 下面是一个perl调试器终端会话的一个片段(与两个串和阵列/列表办法):
$ perl -d
Loading DB routines from perl5db.pl version 1.32
Editor support available.
Enter h or `h h' for help, or `man perldebug' for more help.
^D
Debugged program terminated. Use q to quit or R to restart,
use o inhibit_exit to avoid stopping after program termination,
h q, h R or h o to get additional info.
DB<1> $str="\x00\x00\x84\x00"
DB<2> print $str
�
DB<3> print unpack("H*",$str) # show content of $str as hex via `unpack`
00008400
DB<4> $str2=substr($str,2,2)
DB<5> print unpack("H*",$str2)
8400
DB<6> $str2=substr($str,1,3)
DB<7> print unpack("H*",$str2)
008400
[...]
DB<30> @stra=split('',$str); print @stra # convert string to array (by splitting at empty string)
�
DB<31> print unpack("H*",$stra[3]) # print indiv. elems. of array as hex
00
DB<32> print unpack("H*",$stra[2])
84
DB<33> print unpack("H*",$stra[1])
00
DB<34> print unpack("H*",$stra[0])
00
DB<35> print unpack("H*",join('',@stra[1..3])) # print only portion of array/list via indexes (using flipflop [two dots] operator)
008400
我的性质很迂腐,当我在文档中读到这个时,我发现'character'不明确。我不清楚它是指一个数据单元(即一个字节)还是一个字符串单元(取决于编码) – Mike 2010-06-17 22:03:09
调用'binmode FILE,':raw“或”binmod FILE“:bytes”'将始终无论您的默认IO层如何(例如,如果声明“使用utf8”),以“字节”模式打开文件句柄。 – mob 2010-06-17 22:04:39
我实际上同意使用“字符”对我来说就像是一个bug,尤其是考虑到“Encode(3perl)”中字符,字节和八位字节之间的区别。它恰好是合适的词,但是如果它说“字符(由当前I/O层定义)”,我想我会喜欢它。我猜这也是对你的回答的批评,因为'read'总是读取“字符” - 但有时“字符”被定义为“八位字节”,有时被定义为“UTF-8码位”。 – darch 2012-10-31 16:01:54