reverse-function with regex

P

Pieter Online

Hello,

I'm trying to write a reverse-function with regex,

The following code gives: fedcba
$message = "abcdef";
$message =~ s/(.)(.)(.)(.)(.)(.)/$6$5$4$3$2$1/;
print $message;

But I like to use something like:
$message =~ s/(.){6}/$6$5$4$3$2$1/;
or even
$message =~ s/(.)*/$6$5$4$3$2$1/;

But that does not work, and all I can do is hope one of you can help me
out..

Thanks in advance,
Pieter
 
M

Mirco Wahab

Pieter said:
Hello,

I'm trying to write a reverse-function with regex,

The following code gives: fedcba
$message = "abcdef";
$message =~ s/(.)(.)(.)(.)(.)(.)/$6$5$4$3$2$1/;
print $message;

But I like to use something like:
$message =~ s/(.){6}/$6$5$4$3$2$1/;
or even
$message =~ s/(.)*/$6$5$4$3$2$1/;

But that does not work, and all I can do is hope one of you can help me
out..

$message =~ s/(.*)/reverse $1/eg;

;-)

Regards

M.
 
A

anno4000

Michele Dondi said:
I'm trying to write a reverse-function with regex,
[...]

BTW: I tried doing the same with a single s/// instead of a pattern
match, but it doesn't work:

#!/usr/bin/perl

use strict;
use warnings;

sub myownreverse {
my $s=shift;
$s =~ s/^(.)(.*)/myownreverse($2) . $1/e;
$s;
}

print myownreverse 'abcdef';

__END__

The latter yields

C:\temp>foo.pl
ffedcb

for me... (And I see no simple modification to correct it.)

That's because in the substitution part of s/// the call to
myownreverse() destroys the value of $1 which you are using
in the same expression. Save the initial value to fix it:

sub myownreverse {
local $1;
my $s=shift;
$s =~ s/^(.)(.+)/my $x = $1; myownreverse($2) . $x/e;
$s;
}

I have also changed the second capture from (.*) to (.+). If
(.*) is empty there is nothing to do.

Anno
 
T

Ted Zlatanov

I'm trying to write a reverse-function with regex,

The following code gives: fedcba
$message = "abcdef";
$message =~ s/(.)(.)(.)(.)(.)(.)/$6$5$4$3$2$1/;
print $message;

But I like to use something like:
$message =~ s/(.){6}/$6$5$4$3$2$1/;
or even
$message =~ s/(.)*/$6$5$4$3$2$1/;

But that does not work, and all I can do is hope one of you can help me
out..

Regular expressions can't reverse arbitrary strings, it's not part of
their functionality. The only way is to do s/(.*)/reverse($1)/e which
of course is better written as $message = reverse $message;

Ted
 
P

Pieter Online

Thank you guys,
you're amazing!!!

The recursive function was great and you're explanation really helped
me to improve my regex juggling skillz.

Best regards,
Pieter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top