Table of Contents

A little more control over the premature ending: Labels

So that's easy enough. But wait! We need a medical, human-fixer type doctor, not just anyone with a PhD. So, the same principle applies in this example here:

@names  =('Mrs Smith','Mr Jones','Ms Samuel','Dr Jansen','Sir Philip');
@medics =('Dr Black','Dr Waymour','Dr Jansen','Dr Pettle');

foreach $person (@names) {
	print "$person\n";
	if ($person=~/Dr /) {
		foreach $doc (@medics) {
			print "\t$doc\n";
			last if $doc eq $person;
		}
	}
}

Aside from showing one way to indent your code, this also demonstrates a nested loop. A nested loop is a loop within a loop. What happens is that the @names array is searched for a 'Dr ', and if it is found then the @medics array is searched to make sure the doctor is a human-fixing doctor not a professor of physics or something. The regular expression has been shifted into an if statement, where it works nicely as it only returns true or false.

The problem with the code is that after we find our medical doctor we want it to stop. But it doesn't. It only stops the loop it is in, so Dr Pettle never gets printed. However, the code just carries on with Sir Philip who is terribly sorry old chap, but can't be of any bally use at all, what ho! What we need is a way to break out of the entire loop from within a nest. Like so:

@names  =('Mrs Smith','Mr Jones','Ms Samuel','Dr Jansen','Sir Philip');
@medics =('Dr Black','Dr Waymour','Dr Jansen','Dr Pettle');

LBL: foreach $person (@names) {
	print "$person\n";
	if ($person=~/Dr /) {
		foreach $doc (@medics) {
			print "\t$doc\n";
			last LBL if $doc eq $person;
		}
	}
}

Only two changes here. We have defined a label, namely LBL. Instead of breaking out from the current loop, which is the default, we specify a label to break out to, which is in the outer loop. This works with as many nested loops as your brain can handle. You don't have to use uppercase names but for namespace reasons it is recommended, and you can call your labels whatever you please. I was just being unimaginative with the name of LBL, feel free to invent labels called DORIS or MATILDA if that's what floats your personal boat.