ЭЛЕКТРОННАЯ БИБЛИОТЕКА КОАПП |
Сборники Художественной, Технической, Справочной, Английской, Нормативной, Исторической, и др. литературы. |
1.6. Reversing a String by Word or CharacterProblemYou want to reverse the characters or words of a string. SolutionUse the $revbytes = reverse($string); To flip words, use $revwords = join(" ", reverse split(" ", $string)); DiscussionThe $gnirts = reverse($string); # reverse letters in $string @sdrow = reverse(@words); # reverse elements in @words $confused = reverse(@words); # reverse letters in join("", @words) Here's an example of reversing words in a string. Using a single space, " ", as the pattern to # reverse word order
$string = 'Yoda said, "can you see this?"';
@allwords = split(" ", $string);
$revwords = join(" ", reverse @allwords);
print $revwords, "\n";
We could remove the temporary array $revwords = join(" ", reverse split(" ", $string)); Multiple whitespace in $revwords = join("", reverse split(/(\s+)/, $string)); One use of $word = "reviver"; $is_palindrome = ($word eq reverse($word)); We can turn this into a one-liner that finds big palindromes in /usr/dict/words. % perl -nle 'print if $_ eq reverse && length > 5' /usr/dict/words See AlsoThe |