看到一个字符串处理题目,把一个字符串的每个字符的ascii码增加2再打印出来。自己写了一个perl小程序练练手,但是觉得用得不是很简单,后来请教了一下瑞典同事Stefan,他给了一个simple solution, really cool, orz...
==========我的程序===============
#!/usr/bin/perl
my $test;
while (<>){
# s/\b([a-z])(\w+)\b/\u$1$2/g;
# $test =~ s/(\w)/($1)+2)/g;
@a=split//;
$cd=@a;
foreach (@a) {
if ($_ eq ' '){
print chr(ord($_));
}
else{ print chr(ord($_)+2);}
}
print "\n";
# print $_;
}
==========他的程序===============
use strict;
my $string = "abcdefg";
my @ascii = map { $_ + 2 } unpack("C*", $string);
my $string2 = pack("C*", @ascii);
print $string . ' -> ' . $string2 . "\n";
阅读(2160) | 评论(1) | 转发(0) |