Lesson 17 of 55
8 mins readPython Labeled Loops & Nested Control
In Plain English
Perl supports loop labels (conventionally in `UPPERCASE:`) allowing `last LABEL;` or `next LABEL;` to break or continue outer loops from deep inside nested loops.
Deep Dive: How It Works
Label Syntax: Place `LABEL:` immediately before `for`, `while`, or `until`.
Targeted Control: `last OUTER;` terminates the named outer loop, not just the inner one.
Matrix Search: Ideal for exiting multi-dimensional scans when a match is found.
Core Rules to Remember

Uppercase Convention: Labels are usually uppercase identifiers (e.g., `OUTER:`, `ROW:`).

Multi-Level Break: Allows exiting multiple nesting levels cleanly.
Live Interactive Example
Hit Run Code to see it liveBreaking Outer Loop on Match
Python 3.12
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Output Console
Click "Run Code" to view the rendered output.
How it works: last OUTER immediately terminated both inner and outer loops.
Your Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Micro Exercise
Break Nested Loop with Label
Label an outer loop `ROW: for my $i (1..3)`.
Inside an inner loop `for my $j (1..3)`, if `$i == 2`, call `last ROW;`.
Otherwise print `"[$i,$j] "`.
1
2
3
4
5
Sandbox Output
Click "Run & Check" to test your solution.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.