請允許我發表一個關於將字符串視爲二進制數組的小例子 - 因爲我自己發現很難相信所謂的「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