sub keyword to create a new function (subroutine):
sub say_hi { print "Hello, world!\n"; }
&" sign before, the name of the function.
# function is called say_hi(); # function is called again &say_hi; # ... lots of code ... # function is declared sub say_hi { print "Hello, world!\n"; } # function is called a third time say_hi;
@_ special array.my @array1 = (1 , 2 , 3); my @array2 = (4 , 42); print_sum(@array1 , @array2); # inside print_sum, @_ = (1 , 2 , 3 , 4 , 42) # This is the same thing that happens when you write: my @array3 = (@array1, @array2);
shift operates by default on the @_ array.@_ array is an alias, not a copy, of the input parameters.sub func1 { my @params = @_; # create a copy of the input parameters } sub func2 { my $param1 = $_[0]; # an example of copying the input my $param2 = $_[1]; # parameters one by one. } sub func3 { my $param1 = shift; # shift works by default on @_ my $param2 = shift; # }
sub increment_all { for (@_) { ++$_; } } my @nums = qw(3 8 -2 41); print "Orig numbers = @nums\n"; increment_all(@nums); print "New numbers = @nums\n";
return statement:
sub sum { my $sum; for (@_) { $sum += $_; } return $sum; } my $answer = sum(7,13,22);
sub cool_sub { # function code... return @array1, @array2; } # silly mistake: my (@big_array, @empty_array) = cool_sub();
my @array1 = qw(a b 5); my @array2 = qw(a b 6); if (compare_arrays(\@array1,\@array2)) { print "Same!\n"; } else { print "Different!\n"; } sub compare_arrays { my %count; my @first_array = @{$_[0]}; my @second_array = @{$_[1]}; for (@first_array,@second_array){++$count{$_}} for (values %count) {return 0 if ($_ ne 2)} return 1; }
sub some_func { my (@array1, @array2); # func code... return \@array1, \@array2; } my ($a1ref, $a2ref) = some_func(); my @a1 = @{$a1ref}; my @a2 = @{$a2ref};
sub { my $arg = shift; $arg =~ s/,/_/; return $arg; };
my $input = eval `cat infile`; my @input_args = ("a,a\n" , ",b\n" , "c,d\n"); my @transformed_args = simple_transform(\@input_args,$input); print for @transformed_args; sub simple_transform { my @args = @{$_[0]}; my $transform = $_[1]; my @output; for my $arg (@args) { push @output, &$transform($arg); } return @output; }
use Getopt::Long; my $data = "file.dat"; my $length = 24; my $verbose = 0; my $help = 0; my $result = GetOptions ( "length=i" => \$length, "file=s" => \$data, "verbose" => \$verbose, "quiet" => sub { $verbose = 0 }, "help|man" => \&help, ); sub help {die "Usage stagement...\n"}
perldoc perlsub is the authoritative reference about Perl subroutines.perldoc perlfunc will help you with info about Perl's builtin functions.perldoc -f <function> will help you with info about a specific builtin function.
Offer Kaye. YAPC::Israel::2005.
Slides automatically generated by tmpl2slides.pl. Last updated on Wed Feb 9 23:11:09 2005