-1

As you would see below is a bad perl practice of 'eval' a scalar containing code. That aside, in the following code, the condition '$condition{'b'}{'1'}' was not run through the loop. Only the condition that came first in the array ran, ie. condition '$condition{'a'}{'1'}', was run.

my @parameter=('a','b');

my %condition;
$condition{'a'}{'1'}='$degree>=5';
$condition{'b'}{'1'}='$number>5';

foreach (@parameter) {
   my $count=0;

   foreach (<INPUT>) {
   my $degree=....;  #$degree defined
   my $number=.....; #$number defined
   if (eval $condition{$_}{'1'}) {$count++}  #only $condition{'a'}{'1'} was run!
   }

}

The first question is why did the first condition got stuck in the loop and the second question is how can I fix it? Would really appreciate any help/advise/solutions. :)

noqa
  • 313
  • 2
  • 4
  • 11
  • The answer depends crucially on what that ".." is. – Sean Aug 15 '12 at 22:23
  • 1
    This question gives the impression that no progress was made after all the answers to http://stackoverflow.com/q/11976045/716443 However, you should probably be testing `$@` to see if `eval` generated an error. Otherwise, your problem exists within the unseen code contained within `{..}`. And then go back and use one of the solutions that didn't require evaluating strings as code. – DavidO Aug 15 '12 at 22:26
  • stackoverflow.com/q/11976045/716443 did help to get the condition working for the first element in the array, but then it got stuck. – noqa Aug 15 '12 at 22:41
  • Try this: `my $result = eval $condition{$_}{1}; die $@ if $@; if( $result ) { $count++ }`. It won't magically fix the problem, but might prevent a silent failure from causing programmer confusion. – DavidO Aug 15 '12 at 22:42
  • thanks for the help, but it did not make a difference. Returns $count=0 for the second in the array with no warning. – noqa Aug 15 '12 at 23:00
  • At the point of the `eval` `$_` contains the last line read from `INPUT`, not the current element of `@parameter`. Becuase you haven't used `chomp` it will include a newline and so won't match any of the hash keys – Borodin Aug 16 '12 at 02:06

1 Answers1

1

The foreach (@parameter) loop runs its body for 'a'. Within that loop the foreach (<INPUT>) loop consumes the input to its end.

The foreach (@parameter) loop then runs its body for 'b'. Within that loop the foreach (<INPUT>) loop has no input because it has already been consumed.

MRAB
  • 20,356
  • 6
  • 40
  • 33