Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: problem with foreach statement

by sk (Curate)
on Dec 31, 2005 at 21:19 UTC ( #520191=note: print w/ replies, xml ) Need Help??


in reply to problem with foreach statement

You are looping 8 times. You are printing it is new error before you check all possible elements. I have modified your code to fix this issue. Second part of the code is using a hash. It is much better way to check if elements are present.

#!/usr/bin/perl use strict; use warnings; my @exerrors = (123,456); my %adv79 = (123=>1,456=>1,789=>1,777=>1); my $flag = 0; foreach my $adv79key (keys %adv79) { $flag = 0; foreach my $exerrors (@exerrors) { if ($adv79key == $exerrors) { print "$adv79key is an old error\n"; $flag = 1; last; } } print "$adv79key is a new error\n" if (0 == $flag); } print $/; my %newerr = map {$_ => 1} @exerrors; foreach my $adv79key (keys %adv79) { if (exists($newerr{$adv79key})) { print "$adv79key is an old error\n"; } else { print "$adv79key is an new error\n"; } }

Output

456 is an old error 123 is an old error 789 is a new error 777 is a new error 456 is an old error 123 is an old error 789 is an new error 777 is an new error

update: fixed typo


Comment on Re: problem with foreach statement
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://520191]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (11)
As of 2015-07-30 17:13 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (273 votes), past polls