Method 1: The Standard split, reverse, join Approach
This is the most common, efficient, and readable way to reverse words in a string within a standard Perl script.
# Split the string by spaces, reverse the resulting list of words,
# and join them back together with a space delimiter.
my $reversed = join(" ", reverse(split(/ /, $string)));
Method 2: Perl One-Liners (Command Line)
Perl excels at quick text manipulation directly from the shell. Here are two ways to do it on the fly:
Option A: Splitting by non-word characters
# Splits the input by non-word characters (\W+), reverses the list,
# and joins it using the default list separator ($") which is a space.
echo "run as fast as you can" | perl -lne 'print join $", reverse split /\W+/'
Option B: Global regex matching
# Matches all word blocks (\w+) globally, reverses the resulting list into array @a,
# and prints the array interpolated in double quotes (which automatically adds spaces).
echo "all your bases are belong to us" | perl -lne '@a = reverse /\w+/g; print "@a"'
Method 3: The Regex and
unshift ApproachThis is a more creative approach that iterates through the string and builds a new array from the front backwards.
$_ = "My name is Jack";
# Find words (\w+) globally. For each word found, prepend it (unshift)
# to the default array (@_) along with a trailing space.
unshift @_, "$1 " while /(\w+)/g;
# Print the resulting array, which now contains the reversed sentence.
print @_;
No comments:
Post a Comment