Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number

Re: Reverse String

by bimleshsharma (Beadle)
on Jul 21, 2011 at 06:11 UTC ( #915796=note: print w/replies, xml ) Need Help??

in reply to Reverse String

Try this

$line = 'Bimlesh Sharma';
$line =~ s/(\w+)/ scalar (reverse($1)) /eg;
print $line;
# prints "hselmiB amrahS"

Replies are listed 'Best First'.
Re^2: Reverse String
by davido (Archbishop) on Jul 21, 2011 at 06:50 UTC

    I understand what you're doing here; reversing individual "words" (by Perl's definition of what matches against \w), while preserving their original position within the string. If you were actually reversing the string (as your original post implies), you would just use reverse $string, taking context into consideration.

    Going back to your solution for a moment: \w matches alpha characters, plus 0-9 and underscore, but not hyphen or apostrophe. So "What's up" becomes "wahW's pu". That may be what you're after, or maybe you would prefer to count apostrophe as a character, so that the string becomes "s'wahW pu". While you're at it you might want to count hyphen (or again, maybe not), so that "hyper-drive" becomes evird-repyh" instead of what happens with your solution, which is 'repyh-evird'. But I'm really not sure what you're after as neither your solution nor my suggestions actually match the most simple and obvious solution to "Reverse string".

    But I do wonder, in posting a question, and immediately following it up with your own answer, if this may be more appropriate in Meditations (where people post interesting discoveries, thoughts, ...meditations), or Cool Uses For Perl (where people post snippets of code that show Perl doing interesting things). I would say Categorized Questions and Answers, except that has been a pretty slow category for a few years here.


Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://915796]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (6)
As of 2018-02-22 21:45 GMT
Find Nodes?
    Voting Booth?
    When it is dark outside I am happiest to see ...

    Results (299 votes). Check out past polls.