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

Dear perlmonks,

Why is the code underneath worthy a syntax error, I do know that it is poorly written and inconvenient but that due to my novice writing skill:). Thank you so much in advance

foreach @allcards { if ($allcards[$count] != @userinput[0])||$allcards[$count] != @userinp +ut[1] || $allcards[$count] != @userinput[2] || $allcards[$count] != @ +userinput[3] || $allcards[$count] != @userinput[4] || $allcards[$coun +t] != @userinput[5] || $allcards[$count] != @userinput[6]) { push (@resthand,$allcards[$count]); } $count++; }

Replies are listed 'Best First'.
Re: Syntax error if clausule
by davido (Cardinal) on Aug 15, 2012 at 10:10 UTC

    It's customary to specify what error message you're getting.

    • foreach @allcards {: Missing parens around @allcards.
    • if( $allcards[$count] != @userinput[0] ) ||... Your conditional statement is cut short by a closing paren, and everything that comes after is a problem.

    Those constructs are explained pretty clearly in perlintro and perlsyn.

    Another issue: @somearray[1] is an array slice. While it's syntactically correct, it's semantically mistaken to use an array slice when you really mean to refer to a single element by its index. $somearray[1] would be the semantically proper way to do that.


    Dave

Re: Syntax error if clausule
by aitap (Curate) on Aug 15, 2012 at 10:57 UTC
    Let me optimise your code for you:
    • Firstly, you don't have to calculate $count manually. foreach does everything for you, just use $_ instead of $allcards[$count]. Or, better (see next): foreach my $card (@allcards) { ... }
    • Secondly, you want to check all elements of @userinput indexed from 0 to 6. You can do it using array slice and grep:
      grep { $_ != $card } @userinput[0..6]
      As long as grep returns arrays, you can just push it to your @resthand array.
    The resulting code is:
    foreach my $card (@allcards) { push @resthand, grep { $_ != $card } @userinput[0..6]; }
    Sorry if my advice was wrong.
      Thanks you guys so much:)