Perl subroutines

How to make subroutines

sub test {
}

Add sub identifier.
How to use this?

&test;

Return value

sub res_val {
   $n;     
}

Arguments

$_[0], $_[1]; is arguments(@_ is arguments)
example

sub max {
   # Compare
   if ( $_[0] > $_[1] ) {
       $_[0];
   }
   else {
       $_[1];
   }
}
$max_val = &max(3, 5);
print "max is $max_val\n";

If you exceed number of argument lie $max(1,2,3); 3 is ignored.

Use private vars in subroutines

Use my

sub min {
	my($m, $n);		# new private vars for this block
	($m, $n) = @_;
	if ( $m < $n ) {
		$m
	}
	else {
		$n;
	}
}
print ("Min is " . &min(2,4) . "\n");
&#91;/perl&#93;
One line
&#91;perl&#93;
my($m, $n) = @_;   # fine
&#91;/perl&#93;

Oh!, return is not needed. Its's optional.

<h3>Check arguments number</h3>
[perl]
sub max2 {
   if ( @_ != 2 ) {
   		print "Warinng max2 should get exact two arguments\n";
   }
}

&max2(1,2,3);   # Oops!

&

& is to differentiate from general module.

state

Nice description is PerlMonks.
This is persistent vars.