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

Hello :) Consider this bit of code.
my $stri="abctest"; my @one=('a','b','c','d','e','f','g'); my $part; my $lone=@one; my $first_char=substr($stri,0,1); #print "\n$first_char"; my $second_char=substr($stri,1,1); #print "\n$second_char"; my $third_char=substr($stri,2,1); #print "\n$third_char"; if ($first_char eq 'a' || $first_char eq 'b'){ for(my $ne=0;$ne<$lone;$ne++){ if ($second_char eq $one[$ne]) { if ($third_char ne 'c' || $third_char ne 'd'){ $part=substr($stri,0,2); print "\nThe string in part:"; print"\n$part"; } } } } if ($first_char eq 'a' || $first_char eq 'b'){ for(my $ne=0;$ne<$lone;$ne++){ if ($second_char eq $one[$ne]){ if ($third_char eq 'c' || $third_char eq 'd'){ $part=substr($stri,0,3); print "\nThe string in part:"; print"\n$part"; } } } }
When we run the above code with $stri equal to "abctest" we should get a match in the second section of loops only
i.e. if the first char in the string is 'a' or 'b' , second char is any of the elements of @one, and third char is 'c' or 'd'.
The value of part should be 'abc'.

But there is a match in both the sections of loops, and this is the output I get:
The string in part: ab The string in part: abc
This comparison does not seem to be working:
if ($third_char ne 'c' || $third_char ne 'd'){ $part=substr($stri,0,2);
What is the mistake here?
Thanx :)

Replies are listed 'Best First'.
Re: Loops and comparisons
by gjb (Vicar) on Oct 15, 2003 at 12:28 UTC

    I'm not sure what you're after exactly, but I suppose you want the first "loop" to match when the third character is neither a 'c' nor a 'd'. Hence the condition should read

    if ($third_char ne 'c' && $third_char ne 'd'){ $part=substr($stri,0,2);

    Incidently, there are more elegant ways to check whether  $second_char is in @one. Have a look at grep, or alternatively, you can use a regexp.

    my $regexStr = join("|", @one); my $regex = qr/^$regexStr$/; ... if ($second_char =~ $regex) { ...
    Both approaches eliminate the need for the for loop.

    Hope this helps, -gjb-

      Hi :),
      using || instead of && was a silly mistake.But using a regexp instead of a for loop helps, makes the code less cluttered.
      Thanx:)
Re: Loops and comparisons
by snax (Hermit) on Oct 15, 2003 at 13:28 UTC
    You say:

    This comparison does not seem to be working:

    if ($third_char ne 'c' || $third_char ne 'd'){ $part=substr($stri,0,2);
    What is the mistake here?

    I guess it depends upon what you mean by "not working"; I assume you are aware that it is unlikely that any single character would fail to satisfy your test?

    :)

    Draw a Venn diagram :) :)