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

foreach(@ARGV) { if($_ eq "complete") { $change = "cmplt"; } else if($_ eq "srces") #syntax error 1 { $change = "src"; } else #syntax error 2 { push($printof{$change},$_); } }
my compiler insists, that there are syntax errors at the commented positions - are there?. i would appreciate any help on this topic, for i tried it to often to be able to see the obviously...

with kindest regards ;)
m.t.minded

Replies are listed 'Best First'.
Re: i cant see whats wrong with this:
by BrowserUk (Patriarch) on Aug 30, 2002 at 08:57 UTC
      really? i used the  if(cond){block}else if(...){...} construction in several perlscripts and there, they worked just fine.
      but i'll try it your way. thx...
      --> it seems to work....

        Directly from perlman:perlsyntax manual.

        The following compound statements may be used to control flow: if (EXPR) BLOCK if (EXPR) BLOCK else BLOCK if (EXPR) BLOCK elsif (EXPR) BLOCK ... else BLOCK LABEL while (EXPR) BLOCK LABEL while (EXPR) BLOCK continue BLOCK LABEL for (EXPR; EXPR; EXPR) BLOCK LABEL foreach VAR (LIST) BLOCK LABEL foreach VAR (LIST) BLOCK continue BLOCK LABEL BLOCK continue BLOCK

        Do you see a syntax diagram for

        if(cond){...} else if(cond) {...} else {...} there anywhere?

        Sorry! I don't know what language you were using, but it wasn't Perl!


        Well It's better than the Abottoire, but Yorkshire!
Re: i cant see whats wrong with this:
by tommyw (Hermit) on Aug 30, 2002 at 09:09 UTC

    The syntax of else specifies that it must be followed by a block.

    So

    foreach (@ARGV) { if ($_ eq "complete") { $change="cmplt"; } else { if ($_ eq "srces") { $change="src"; } else { push ($printof{$change}, $_); } } }
    would be legal, if horrible. Otherwise you need to use elsif. A more scalable solution would be to use a hash instead.

    Of course, if the argument is neither "complete" nor "srces" then $change is not being initialised (in the code shown), so that default push may not be doing the right thing anyway...

    --
    Tommy
    Too stupid to live.
    Too stubborn to die.

Re: i cant see whats wrong with this:
by LeGo (Chaplain) on Aug 30, 2002 at 12:35 UTC
    The problem is simple. You are using "else if" it should be "elsif".

    LeGo