views:

420

answers:

3

I find that using labels inside Perl subroutines, to break from multiple loops, or to redo some parts with updated variables, very helpful. How is this coding style seen by the community? Is using labels inside subroutines frowned upon?

+13  A: 

No. They serve exactly the purpose your describe and I consider them a nice feature of the language that gets used too little.

On the other hand, whenever I find myself pondering the use of a label, I also find myself wondering whether my code needs a little refactoring.

innaM
In most cases, I think the code is clearer with the use of labels. Rewriting code so that it doesn't use them anymore usually leads to many lines of extra code.
Geo
Sometimes it does, sometimes it doesn't. I always go for the code that is easier to read and understand. Sometimes that's the code that uses labels.
innaM
Perl Best Practices is in favor of labels. I don't agree with all of PBP but I think this is one of its pieces of good advice. They serve as documentation if nothing else.
hobbs
+10  A: 

Using labels with next, last, and redo is fine, but you should pause to consider whether the code structure is the best one. In my experience you rarely need to use these operators on anything other than the enclosing loop (which means you don't need to use a label).

Using goto LABEL is strongly discouraged.

Michael Carman
+5  A: 

There is usually no reason to use goto LABEL.

For example:

my $i = 10;
Label:
# ...
goto Label if --$i;

Is better written as:

my $i = 10;
{
  # ...
  redo if --$i;
}


The only reason I can think of to use a label, is to break out of multiple loops, or to continue an outer loop.

my $i = 10;
OUTER: while(1){
  # ...
  while(1){
    # ...
    last OUTER unless --$i;
  }
}
my $i = 10;
OUTER: {
  # ...
  {
    # ...
    redo OUTER if --$i;
  }
}
Brad Gilbert