Goto vs. Local function in Perl

770 views Asked by At

In Perl, is it better to use goto or local function, and why with an example?

For example, I am using a code

sub data {
    data;
}

data();

or

goto L:

L: if ( $i == 0 )
   print "Hello!!!!";
2

There are 2 answers

5
simbabque On BEST ANSWER

Programmers don't die. They just GOSUB without RETURN.

That said, do not use goto in Perl.

  • If you want a statement to be executed once, just write that statement and don't use any flow control
  • If you want your program to execute the stuff several times, put it in a loop
  • If you want them to be executed from different places, put them in a sub
  • If you want the sub to be available in different programs, put them in a module
  • Don't use goto

There is one place where a goto makes sense in Perl. Matt Trout is talking about that in his blog post No, not that goto, the other goto.

0
zgpmax On

Conventional wisdom is that other constructs are better than goto.

If you want to do something repeatedly, use a loop.

If you want to do something conditionally, use a block with if.

If you want to go somewhere and come back, use a function.

If you want to bail out early and "jump straight to the end", this can often be better written using an exception. (Perl handily manages