« Big Spiders | Main | Final Scratch »

Killer Loop

Obvious Statement Alert
I know this stuff is elementary to most of you peeps who peek at this blog every so often, but I thought this was a nice feature.
I have been working on a system to send electronic offers to students, the system was all ready to go tomorrow when some of the lecturers decided they did not want their students enrolling just yet.
My data came in a .CSV I was looping through it and sending out offers by email, so I needed to find a way of killing the loop if the course id equalled something.
Normally I would do

if ($cid eq "F9YHTC"){
  donothing
}else{
  dosomethingelse
}

Then I remembered something about LABELS from way back in Blackstar, so I found the chapter in my Programming Perl book and found this nice way of ending a loop if a pattern is matched.

LINE: while (<STDIN>){
  next LINE if ($cid eq "F9YHTC");
}

In other words label the loop and tell it to take the next line if that one matches something.

Comments

The "if(...){ do_nothing }" part of your original solution is a bit of a red flag. You probably want to use "unless(...){ do_something }" instead, or "if ($something ne $something_else) { do_something }" or possibly "do_something unless ...".

Also, in your labeled example, you don't even need the label. You can just say "while(...) { next if ...; do_something }".

You missed the code review evening in Belfast.PM on Monday, we'll probably do it again next month if you want to submit some code...

No serious it wouldn't be fair to other programmers who take their work seriously. I hack something together, to perform a task. Most of my code runs from my home directory and tidies databases or does mailouts, it wouldn't be interesting enough to submit for review.

Post a comment

The following bizarre question is in place to try to stop Comment Spam.