in reply to Re: reverse a string in place
in thread reverse a string in place

I don't know how old this thread is but I found it interesting to practice manipulation for strings,

please keep in mind that I am but a few weeks into this perl code but did I meet the requirements? other than using length or split

use strict; use warnings; my $string = 'abcdefghi'; #let's find the ways to count the elements in string; my $l = length($string); #finding number of elemnts my @ind=split //,$string; #finding the number of elements #assigning the start of our last element for our looping my $n = (scalar @ind )-1; #getting the last element to start count bac +kwards optinal for (my $i=(length ($string)-1) ; $i >= 0; $i-- ){ print $ind[$i]; } print "\nfor comparison :", scalar reverse($string),"\n";

Replies are listed 'Best First'.
Re^3: reverse a string in place
by stevieb (Canon) on Jun 28, 2015 at 01:26 UTC

    Good job, especially the use strict; use warnings;. Here's another way based on your code that you may find interesting. (EDIT: My bad... I totally glanced over the fact no built-ins were allowed).

    while (my $letter = pop @ind){ print $letter; }

    pop() removes the last element of an array. Also see shift(), unshift() and push()

    -stevieb

      "without using any other array or built-in function"

      yeah, I had no idea how to get the number of elements without the use of at least one build-in option.

      Also, the no use of array is tricky for me.

      I think I will use these questions that other asks to practice my code but sometimes it is difficult to understand what a piece of code without a little help with comments.

      but then again, I am learning so everything is a little tricky...hmm, sometimes I think I should have picked to learn the piccolo over the summer ;-)

      is is a nice function

      and now playing with shift and unshift to implement into next little prog

      thanks

        Here's a couple very common example use cases for shift, unshift, push. The @INC array is special in Perl, and is used to store directories where libraries are housed. To add a custom location, it's common to unshift @INC

        The most common use of shift is extracting parameters from the special @_ array within a subroutine. @_ in Perl is the default array, and is implicitly used to store all parameters going into a subroutine. In the shift line I don't say shift @_;, because the @_ is implicit.

        In the last example, I use push to add elements to a new array based on contents from a different array.

        #!/usr/bin/perl # unshift print "$_\n" for @INC; unshift @INC, '/home/steve/my_lib_dir'; print "$_\n" for @INC; # shift parameter("Hello, world!"); sub parameter { my $param = shift; print "$param\n"; } # push my @numbers = qw(1 2 3 4 5); my @totals; for my $elem (@numbers){ push @totals, $elem + 5; } print "$_\n" for @totals;

        -stevieb