RCRAMER.COM
Clever website slogan
Home > Tech > Perl > Subroutines
Prev

Perl Notes

Next

Chapter 18. Subroutines

A subroutine is a block of statements that will be executed when the subroutine is called.

&my_subroutine; sub my_subroutine { print "My Subroutine\n"; }

Passing & returning variables to/from a subroutine: The @_ array


Returning variables from a subroutine:

$return=&mySubroutine($sent); sub mySubroutine { my $local_sent=$_[0]; $local_sent++; return $local_sent; }

When passing data to a Perl subroutine, you can pass data items in order or you can name the parameters. Passing in order means that you must remember in which order they were passed. When passing by name, you can lookup the name (also see hashes).

#!/usr/bin/perl $fname = "john"; $lname = "smith"; $payrate = 34.44; $hours = 55; calcData( firstname=>$fname, lastname=>$lname, payrate=>$payrate, hours=>$hours); sub calcData() { %args = @_; print "value of lastname is $args{lastname}"; }

Using external perl subroutines


You can store subroutines in an external file. There's no need for the shebang or execute permissions but, the last line of the file should be 1; (return value). Files that contain subroutines typically use the .lib file extension.

#!/usr/bin/perl require 'subnet.lib'; # Can use relative or full paths ### Attempting to call subnet_estimate in subnet.lib print "\nAttempting to call subnet_estimate in subnet.lib\n"; $IP="64.68.70.132" print "IP Address: $IP\n"; $subnet=&subnet_estimate($IP); # $_[0] or @_ print "Estimated subnet: $subnet\n"; ### Attempting to call subnet_parse in subnet.lib print "\nAttempting to call subnet_parse in subnet.lib\n"; @array=&subnet_parse($IP,$subnet); # $_[0]=$IP, $_[1]=$subnet & @_=both print "Array: @array\n";