"be consistent" PerlMonks

### Re: reverse a string in place

by ww (Archbishop)
 on Mar 24, 2013 at 17:07 UTC ( #1025164=note: print w/replies, xml ) Need Help??

in reply to reverse a string in place

When you ask the Monks to do your homework, it's well to make note of that fact in your initial post.

Otherwise, someone with a spark of evil might just post code to do the job with such sophistication that your instructor will immediately know you've been cheating.

If you didn't program your executable by toggling in binary, it wasn't really programming!

Replies are listed 'Best First'.
Re^2: reverse a string in place
by davido (Archbishop) on Mar 24, 2013 at 21:32 UTC

No built-in functions (abundant use of Perl's operators, though).

Yes, there's a spark of evil. But "they" always say that the easiest way is to divide a problem into smaller sub-problems:

```sub rec_reverse {
return \$_[0] if \$_[0] eq '';
my( \$char, \$smaller_problem ) = \$_[0] =~ m/\A(.)(.*)\z/s;
return rec_reverse( \$smaller_problem ) . \$char;
}

print rec_reverse( "Hello\nworld." ), "\n";

I wouldn't call it sophisticated or elegant though, and if it were turned in as ones own work, it would probably merit some skepticism. Recursion is not an optimal approach here, since the number of recursive calls will match the length of the string, and each call added to the call-stack has a cost. Also, the regexp contortion as a means of eliminating any "built-in" functions (ie, substr) does nothing to dispel the rumor that Perl is difficult to read.

I find with recursion that it always helps me to think through it by thinking in terms of "problem" and "smaller_problem". I'm always tempted to write recursion like this:

```sub rec_reverse {
my \$problem = shift;
if( \$problem eq '' or ! defined \$problem ) {
return \$problem;    # Can't be made smaller. End case.
}
else {
my( \$char, \$smaller_problem ) = \$problem =~ m/\A(.)(.*)\z/s;
return rec_reverse( \$smaller_problem ) . \$char;
}
}

Which is the same thing but more explicit, and possibly more readable (and possibly less, since we've lost variable names that look like strings).

Dave

Create A New User
Node Status?
node history
Node Type: note [id://1025164]
help
Chatterbox?
 [SuicideJunkie]: That's a dumb comparison. If you want to compare equivalent things, you should ask about battery+motors vs fuel tank+engine+ transmission.

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (10)
As of 2017-08-22 18:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
Who is your favorite scientist and why?

Results (339 votes). Check out past polls.

Notices?