CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Intermediate:
Looping making me loopy

 



AndyNemenz
Deleted

Apr 6, 2001, 7:57 AM

Post #1 of 4 (403 views)
Looping making me loopy Can't Post

i keep getting multiple outputs from my loop on failure of the if statement at the bottom of my routine, plz explain why and maybe a solution. Here is the code.

%masterhash = @masterarray;
foreach $item (keys %materhash) {
if ($masterhash{$item} eq $pass && $item eq $user) {&openloc; last;}
else { &header;
print "something is wrong"
&footer; }

This routine takes input from a file line by line , splits off the needed info and groups them in a Hash (user and he). Then i test against the hash entrys to validate the forms input. I know this is not the right way, but i dont know the right way or i would do it, heheh.



japhy
Enthusiast

Apr 6, 2001, 10:17 AM

Post #2 of 4 (398 views)
Re: Looping making me loopy [In reply to] Can't Post

Larry Wall is quoted in saying (and this appeared on the right-hand side of this web site, in the "Wit from the Wall" section):

"Doing linear scans over a hash is like clubbing someone to death with an uzi."

If you want to see if a particular key in a hash has a particular value, just do:


Code
if ($hash{$key} eq $value) { ... }

That reduces your code to:


Code
if ($masterhash{$user} eq $pass) { ... } 
else { ... }

Jeff "japhy" Pinyan -- accomplished hacker, teacher, lecturer, and author


japhy
Enthusiast

Apr 6, 2001, 10:20 AM

Post #3 of 4 (398 views)
Re: Looping making me loopy [In reply to] Can't Post

In addition, the reason you get multiple failures is: it fails for EACH key-value pair that doesn't match your criteria. You don't want that. You want it to fail if it's gone through the hash and hasn't matched.

To get that, there's an idiom you might like:


Code
@list = (...); 
for (@list) {
last if $found = is_prime_number($_);
}

if (not $found) { print "no prime number was found" }

Jeff "japhy" Pinyan -- accomplished hacker, teacher, lecturer, and author


ACtheMadScripter
Deleted

Apr 6, 2001, 1:41 PM

Post #4 of 4 (393 views)
Re: Looping making me loopy [In reply to] Can't Post

This Andy, on a different computer in another location :)
hmm.. i see..and understand! Thank you, i will not be able to implement your advice till tuesday, if i have any trouble ill re-post with new info. But it all sounds logical. You sure have a way of shrinking code, im impressed like always :)


 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives