1.7 以字符或者单词为单位翻转字符串
时间:2006-12-30 来源:xiaoshengcaicai
1.7 以字符或者单词为单位翻转字符串
1.7.1 问题
你想以字符或者单词为单位翻转字符串
1.7.2 解决方案
使用reverse函数在标量上下文里面以字符为单位翻转字符串:
$revchars = reverse($string);
要以单词为单位翻转的话,需要在列表上下文里面使用reverse,同时配合以split跟join函数:
$revwords = join(" ", reverse split(" ", $string));
1.7.3 讨论
reverse函数在标量上下文或和列表上下文里面分别具有不同的功能。在标量上下文的情况下,它把它的所有参数拼合成一个字符串,然后把这个字符串按字符为单位翻转后返回;而在列表上下文时,它只是把它的所有参数(以参数为单位)反序返回一个列表。如果你要用reverse把字符串按字符为单位翻转,除非明显是在标量上下文里面, 否则你得用scalar函数强制声明这是个标量上下文。
$gnirts = reverse($string); # reverse letters in $string
@sdrow = reverse(@words); # reverse elements in @words
$confused = reverse(@words); # reverse letters in join("", @words)
下面是一个把字符串以单词为单位翻转的例子。在split函数里面,模式使用一个只包含一个空格的字符串是一个特例。因为使用这样的模式的话,split会以连续的空格作为分隔符,而且会舍弃结果中的首部空元素(leading null fields),这点就跟awk一样。一般情况下的话,aplit只会舍弃尾部的空元素(trailing null fields)。
# reverse word order
$string = 'Yoda said, "can you see this?"';
@allwords = split(" ", $string);
$revwords = join(" ", reverse @allwords);
print $revwords, "\n";
this?" see you "can said, Yoda
我们可以移掉临时数组@allwords,在一行代码里面实现这样的功能:
$revwords = join(" ", reverse split(" ", $string));
原字符串$string 里面的多个连续空格现在在$revwords里面会编程单个空格。如果你想要保留原字符串的空格,这样写:
$revwords = join("", reverse split(/(\s+)/, $string));
reverse可以用来测试一个单词是不是palindrome(正看和反看这个单词都是一样的)
$word = "reviver";
$is_palindrome = ($word eq reverse($word));
我们可以用这样的一行代码来在/usr/dict/words这个文件里面找到一些比较长的palindromes:
% perl -nle 'print if $_ eq reverse && length > 5' /usr/dict/words
deedeed
degged
deified
denned
hallah
kakkak
murdrum
redder
repaper
retter
reviver
rotator
sooloos
tebbet
terret
tut-tut
1.7.4 参阅
split, reverse, 和 scalar 函数 在 perlfunc(1) 跟Programming Perl 第29章,以及本书里面的1.8这一节里面有