ulaksh has asked for the wisdom of the Perl Monks concerning the following question:

Please let me know where I am doing the mistake.
print "Please enter a string:\n"; $string=<>; chomp ($string); # The first position in the string. $position = 0; while ($position < length($string)) { $char = lc(substr($string, $position, 1)); if ($char ne "a") { last; } # Increment the position $position++; } if ($postion == length($string)) { print "The string you entered is all A's!\n"; } else { print "At least one of the characters in the string " . "you entered is not \"A\".\n"; }
output I am getting everytime is "At least one of the characters in the string you entered is not "A"

Replies are listed 'Best First'.
Re: my script is not giving the result using last function
by marto (Cardinal) on Aug 28, 2012 at 12:47 UTC
    if ($postion == length($string))

    Should be:

    if ($position == length($string))

    adding use strict; use warnings; to your code will help find such mistakes. The remainder of your problem is that if $char is not "a" then you break out of the while loop, at which point $position is still zero and not equal to the length of $string.

    Consider basic debugging of your code, making use of http://learn.perl.org and the tutorials section.

    There are easier ways of achieving your goal, however as a learning exercise I think you should at least figure out everything that's wrong with this approach.

Re: my script is not giving the result using last function
by Corion (Patriarch) on Aug 28, 2012 at 12:42 UTC

    What have you done to debug this problem? At what position in the string does the "non-A" character get found? What character gets found?

    I suggest printing the progress through the string, the position and the length of the string while your loop runs.

    Consider reading readline and chomp.

Re: my script is not giving the result using last function
by Anonymous Monk on Aug 28, 2012 at 12:41 UTC

    You forgot to chomp

    Also, you forgot to rindex instead of substr :)

Re: my script is not giving the result using last function
by philiprbrenan (Monk) on Aug 28, 2012 at 12:58 UTC

    Please consider using a regular expression to perform the validation as it is much simpler to code and faster to execute:

    use feature ":5.14"; use warnings FATAL => qw(all); use strict; use Data::Dump qw(dump); say (/\Aa*\Z/ ? "$_ is all a's" : "$_ is not all a's") for qw(aaaa aaa +ab aaac cccccbbb cccca);

    Produces:

    aaaa is all a's
    aaaab is not all a's
    aaac is not all a's
    cccccbbb is not all a's
    cccca is not all a's
    

      Please consider using a regular expression to perform the validation as it is much simpler to code and faster to execute:

      The point of assignment was probably to learn about substr/index/rindex