Reversing a String by Word or Character
Problem
You want to reverse the characters or words of a string.
Solution
Use the reverse
function in scalar context for flipping bytes.
$revbytes = reverse($string);
To flip words, use reverse in list context with
split and join:
$revwords = join(" ", reverse split(" ", $string));Discussion
The reverse function is two different functions in
one. When called in scalar context, it joins together its arguments
and returns that string in reverse order. When called in list
context, it returns its arguments in the opposite order. When using
reverse for its byte-flipping behavior, use
scalar to force scalar context unless it’s
entirely obvious.
$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 split is a
special case. It causes split to use contiguous
whitespace as the separator and also discard any leading null fields,
just like awk. Normally,
split discards only 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, YodaWe could remove the temporary array @allwords and
do it on one line:
$revwords = join(" ", reverse split(" ", $string));Multiple whitespace in $string becomes ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access