1.split函数
%seen = ( );
$string = "an apple a day";
foreach $char (split //, $string) {
$seen{$char}++;
}
2./(.)/g 但是(.)永远不会是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 .<>是默认的输入流,其实就是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
一个详细的例子:
#!/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函数设置屏幕输出。这里是设置延迟。
}
}