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

I am trying to loop through a array and validate whether its elements are equal to a string, please tell me what is wrong with this code?
foreach $newline(@new2) { if($new2 eq 'QT95EG01') { push(@EG01, $artefact); } if($new2 eq 'QT95EG02') { push(@EG02, $artefact); } }

Replies are listed 'Best First'.
Re: check whether a array element is equal to a string.
by PeterPeiGuo (Hermit) on Jan 10, 2011 at 04:07 UTC

    Use $newline in your comparison.

    Peter (Guo) Pei

      Thank you it works now, I have one more question, coupld you tell me whether this is the correct method to call a perl script from another script?
      if($size_EG12>0){ system "java StopMessageFlows"; foreach(@EG12){ do 'deploy.pl'; } }

        Your script already calls a java program, so simply call other perl scripts in the same way.

        Peter (Guo) Pei

Re: check whether a array element is equal to a string.
by 7stud (Deacon) on Jan 10, 2011 at 06:19 UTC

    Here is the syntax:

    use strict; use warnings; use 5.010; my @answers = qw{yes no maybe}; for my $string (@answers) { say $string; #or do something else to $string }

    Every element of @answers gets assigned to the variable $string in turn.

    There are several perl functions that can be used to call external programs. system() is one of them. One respect in which the functions differ is in their return values.

Re: check whether a array element is equal to a string.
by JavaFan (Canon) on Jan 10, 2011 at 09:58 UTC
    I would write that as:
    @EG01 = ($artefact) x grep {$_ eq 'QT95EG01'} @new2; @EG02 = ($artefact) x grep {$_ eq 'QT95EG02'} @new2;
    assuming @EG01 and @EG02 were empty before the loop. (Otherwise, I'd push to it).

      Looks cool, but won't your solution require grep to loop through @new2 twice (once for each grep)?

      Performance wise, isn't a single foreach loop, with two conditionals better?

        You mean, it's faster to do N * 2 comparisons than 2 * N comparisons?

        If you really care, benchmark. Both will do the same amount of comparisons, but the grep probably uses less opcodes. On top of that, the grep only does one assignment/push per array. Regardless of the number of matches.

        Not that I care. I find the grep version clearer: the important part is the modification (setting or pushing) of the arrays, and they are in front with the grep solution, instead of buried inside the foreach.

        And in general, I'd prefer a solution that doesn't need indentation over one that goes two levels deep. (Deepness of indentation is a rough estimate of complexity (yeah, yeah, hold the counterexamples)).