I am trying to reverse a string of words with this code.
use strict;
use warnings;
print "please enter words to reverse:\n";
my $string = <STDIN>;
chomp $string;
my $rstring = reverse $string;
print "$rstring\n";
For example, when I enter one two three
, the reverse words should be three two one
. But I'm actually getting eerht owt eno
.
Why is this happening?
The computer doesn't know what a word is. When you call reverse
on a string, it will flip around all the characters. But reverse
also allows you to flip around a list of things, which makes more sense in your context.
In list context, returns a list value consisting of the elements of LIST in the opposite order. In scalar context, concatenates the elements of LIST and returns a string value with all characters in the opposite order.
You need to turn your string of words into a list of words, then turn that around, and then turn it back into a string.
If you look at your string, you will notice words are separated by empty space.
V V
one two three
You can split
the string into an array on these spaces. Note that split
takes a pattern as the separator.
my @words = split / /, $string;
Now you have an array of words.
( 'one', 'two', 'three' )
When you reverse
that, it will do it to the elements, not each string inside them, so you get
my @words = reverse split / /, $string;
# ( 'three', 'two', 'one' )
Finally, if you want to put the spaces back in, use the opposite of split
to join
the list into a string again.
print join ' ', reverse split / /, $string;
# three two one
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With