Robert's Perl Tutorial

http://www.sthomas.net/roberts-perl-tutorial.htm


Subroutines -- A First Look

Let's take a another look at the example we used to show how the autoincrement system works. Messy, isn't it ? This is Batch File Writing Mentality. Notice how we use exactly the same code four times. Why not just put it in a subroutine?

$num=10;		# sets $num to 10
&print_results;		# prints variable $num

$num++;
&print_results;

$num*=3;
&print_results;

$num/=3;
&print_results;

sub print_results {
        print "\$num is $num\n";
}
   

Easier and neater. The subroutine can go anywhere in your script, at the beginning, end, middle...makes no difference. Personally I put all mine at the bottom and reserve the top part for setting variables and main program flow.

A subroutine is just some code you want to use more than once in the same script. In Perl, a subroutine is a user-defined function. There is no difference. For the purposes of clarity I'll refer to them as subroutines.

A subroutine is defined by starting with sub then the name. After that you need a curly left bracket { , then all the code for your subroutine. Finish it off with a closing brace } . The area between the two braces is called a block. Remember this. There are such things as anonymous subroutines but not here. Everything here has a name.

Subroutines are usually called by prefixing their name with an ampersand, that is one of these -- & , like so &print_results; . It used to be cool to omit the & prefix but all perl hackers are now encouraged to use it to avoid ambiguity. Ambiguity can hurt you if you don't avoid it.

If you are worrying about variable visibility, don't. All the variables we are using so far are visible everywhere. You can restrict visibility quite easily, but that's not important right now. If you weren't worrying about variable visibility, please don't start. I'd tell you it's not important but that'll only make you worried. (paranoid ?) We'll cover it later.