Press "Enter" to skip to content

Perl labels

I learned about Perl labels and thought I would pass it on. Basically a label names a block of code descriptively. They are usually uppercase. You can use next, redo and last within a labeled block. On the surface this doesn’t seem that useful until you start talking about loops within loops.

Take the following bit of code without labels:


while ( $somecondition ) {
    # do some work
    for my $iterator (1..10) {
        # do some more work
    }
}

Let’s say you want to use next in the for loop to control the while loop. There isn’t way to do that here. You would have to come up with some other logic to handle that. Using labels its very easy:


WHILE:while ( $somecondition ) {
    # do some work
    FOR:
        for my $iterator (1..10) {
        # do some more work
        next WHILE;
    }
}

Of course the above is a meaningless example but you get the idea.

Comments are closed, but trackbacks and pingbacks are open.