1.split函數(shù)
???%seen = ( );
???$string = "an apple a day";
???foreach $char (split //, $string) {
???????$seen{$char}++;
???}
2./(.)/g 但是(.)永遠(yuǎn)不會是newline
???%seen = ( );
???$string = "an apple a day";
???while ($string =~ /(.)/g) {
???????$seen{$1}++;
???}
3.unpack("C*")也可以逐個處理字符:(這個例子是累加字符串里每個字符ascii碼的累加值)
???$sum = 0;
???foreach $byteval (unpack("C*", $string)) {
???????$sum += $byteval;
???}
???print "sum is $sum\n";
???# prints "1248" if $string was "an apple a day"
$sum = unpack("%32C*", $string); #這個方法比上面更快,這個返回32位的checksum值.
4 .<>是默認(rèn)的輸入流,其實就是ARGV.
?????這個模擬sysv的checksum程序:
???#!/usr/bin/perl
???# sum - compute 16-bit checksum of all input files
???$checksum = 0;
???while (<>) { $checksum += unpack("%16C*", $_) }
???$checksum %= (2 ** 16) - 1;
???print "$checksum\n";
???
???Here's an example of its use:
???% perl sum /etc/termcap
???1510
???If you have the GNU version of sum, you'll need to call it with the —sysv option to get the same answer on the same file.
???% sum --sysv /etc/termcap
???1510 851 /etc/termcap
一個詳細(xì)的例子:
#!/usr/bin/perl
# slowcat - emulate a s l o w line printer
# usage: slowcat [-DELAY] [files ...]
$DELAY = ($ARGV[0] =~ /^-([.\d]+)/) ? (shift, $1) : 1; #這里[.]取消了.的特殊性。使其為一般意義。shift移除了@ARGV第一個變量和長度減一。
$| = 1; #不為0就強行清空輸出或打印。
while (<>) { #<>為@ARGV指定的文件句柄
for (split(//)) {
print;
select(undef,undef,undef, 0.005 * $DELAY); #select函數(shù)設(shè)置屏幕輸出。這里是設(shè)置延遲。
}
}