On Wed, 26 Jun 2013 11:57:55 +0100
Rob Dixon <rob.di...@gmx.com> wrote:

> On 26/06/2013 10:32, Shlomi Fish wrote:
> >>
> >> Hi,
> >>
> >>   Could you please let me know how to reverse a string without using built
> >> in function.
> >
> > Do you want to avoid using the
> > http://perldoc.perl.org/functions/reverse.html built-in function or any
> > built-in function whatsoever? Assuming the latter you can do this:
> >

Sorry, I meant that he wished to avoid using reverse() only - not any built-in
function whatsoever.

> > [CODE]
> > #!/usr/bin/perl
> >
> > use strict;
> > use warnings;
> >
> > sub my_reverse
> > {
> >      my ($s) = @_;
> >
> >      my $ret = "";
> >
> >      for my $idx (0 .. length($s) - 1)
> >      {
> >          $ret = substr($s, $idx, 1) . $ret;
> >      }
> >
> >      return $ret;
> > }
> >
> > my $string = shift(@ARGV);
> >
> > print "Reversed is:\n", my_reverse($string), "\n";
> > [/CODE]
> >
> > Running it gives you:
> >
> > [SHELL]
> >
> > shlomif@telaviv1:~$ perl my-reverse.pl Hello
> > Reversed is:
> > olleH
> > shlomif@telaviv1:~$ perl my-reverse.pl Franklin
> > Reversed is:
> > nilknarF
> > shlomif@telaviv1:~$
> >
> > [/SHELL]
> 
> I don't understand. You say you are providing a solution that avoids
> "any built-in function whatsoever", and then use `length` and `substr`.

Yes, see above. Here is a solution without any built-in functions, but with
some built-in operators:

<CODE>

#!/usr/bin/perl

use strict;
use warnings;

sub my_reverse
{
    my ($s) = @_;

    my $ret = "";

    my @chars = ($s =~ /(.)/gms);

    foreach my $c (@chars)
    {
        $ret = $c . $ret;
    }

    return $ret;
}

my ($string) = @ARGV;

print "Reversed is:\n", my_reverse($string), "\n";

</CODE>

You can also do something similar without keeping an array of characters using
something like /\G(.)/gms .

Regards,

        Shlomi Fish

-- 
-----------------------------------------------------------------
Shlomi Fish       http://www.shlomifish.org/
Optimising Code for Speed - http://shlom.in/optimise

Judaism: God knows you will do shit, does nothing to prevent it, but makes you
take the blame for it anyways.

Please reply to list if it's a mailing list post - http://shlom.in/reply .

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to