Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Shaun E on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Reverse the contents of a variable

Status
Not open for further replies.

KevinAr18

Programmer
Apr 25, 2002
309
US
I need to reverse the contents of a variable. I suppose I could come up with a slower or more complex method, but does anyone know a fairly fast or premade way to do it?
 
Code:
$var = reverse $var;

It never hurts to try the obvious. ;)
 
Just figured out... I gotta do this the hard way. I need to reverse things in groups of two.

For example


HE LL O!

would reverse to

O! LL HE
 
#!perl -W
# were u looking for something like this ?
use strict;
print sp_reverse("hello!");
exit;


sub sp_reverse {
my $loop = 0;
my $result = "";
my $mem = length($_[0]) - 2;
while ($loop < length($_[0]) / 2) {
$result .= substr($_[0], $mem, 2);
$loop++; $mem--; $mem--;
}
return $result;
} ---------------------------------------
wmail.jpg


someone knowledge ends where
someone else knowledge starts
 
Neversleep, it fails on 'Hello'. Or any odd length string.

How about something with customisable grouping?
Code:
print group_reverse( 'How are you?', 2 );

sub group_reverse {

	# reverse a string by character grouping
	# omit or set second argument to 0 to reverse entire string.
	# group_reverse( $string, 1 ) is meaningless.

	my( $string, $grouping ) = @_;

	# 0 or undef: reverse the entire string
	return scalar reverse $string unless $grouping;

	my @groups = $string =~ /.{1,$grouping}/g;
	@groups = map $_ = reverse, @groups;
	return join '', @groups;
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top