Steffan Harris
Steffan Harris

Reputation: 9326

If statement failing in Perl

I seem to have problems with this if statement. It logically seems like it works. I want to look to see if the array is defined. If it is defined, look to see if the word matches. But whenever I enter a word that does not match is still seems to be entering the if statement.

if(@split_array and
   ($split_array[0] eq "cd"    or
    $split_array[0] eq "set"   or
    $split_array[0] eq "alias" or
    $split_array[0] eq "last"  or
    $split_array[0])
   )
{

}

Upvotes: 0

Views: 171

Answers (3)

sidyll
sidyll

Reputation: 59287

Try:

if (@split_array and $split_array[0] =~ /^(?:cd|set|alias|last)$/)
{
    # ...
}

Upvotes: 7

TLP
TLP

Reputation: 67900

   ... or $split_array[0]

This part means that if you have a value in $split_array[0] that is defined and not zero or empty, your if will always be true.

Try some formatting to more easily spot mistakes. Like this:

if (
    @split_array and
    (
        $split[0] eq "cd" or 
        $split[0] eq "set" or 
        $split[0] eq "alias" or 
        $split[0] eq "last" or 
        $split[0]
    )
) 
{ ... }

Upvotes: 10

Kendrick
Kendrick

Reputation: 3787

or $split_array[0]))

at the very end of the statement. You aren't comparing it, so I'm guessing that's returning true for any word.

Upvotes: 4

Related Questions