5. Perl Functions/Subroutines

 

 

5.1 Perl User Defined Functions

 

Subroutine:

 

User Defined Functions or Subroutines

 

Define a Subroutine and give it a name:

 

      sub monitor

      {

      statements;

      }

 

Call or use a subroutine with its name and a & symbol:

      &monitor;

 

 

Parameter passing

 

Scope control

 

 

 

 

 

5.2 Examples of Perl User Defined Functions

 

Example 5-1: An example program illustrates how to define and use functions.

 

#!/usr/bin/perl

#func1.pl

#

# OUTPUT:

#  Area of a Circle = 314.159

#  Area of a Square = 100

#

# Define Variables

$radius = 10;      $length = 10;

$width = 10;      $height = 20;

#

# Function Calls

#

$areaC = areaCircle($radius);

$areaSq = areaSquare($length);

$areaRect = areaRectangle($width, $height);

print(" Area of a Circle = $areaC\n");

print(" Area of a Square = $areaSq\n");

print(" Area of a Rectangle = $areaRect\n");

#

# Functions

# Parameter array @_ is used to store all parameters to a function.

# The first element of the parameter array can be retrieved with $_[0].

# The second element of the parameter array can be retrieved with

# $_[1].

sub areaCircle {

    $rad = $_[0];

    return(3.14159 * ($rad ** 2));

}

 

sub areaSquare{

    $len = $_[0];

    return($len ** 2);

}

 

sub areaRectangle {

    ($w, $h) = @_; # $w = $_[0]; $h = $_[1];

    return($w * $h);

}

 

Example 5-2: Understanding function calls and parameter passing

 

#!/usr/bin/perl

#funct2.pl

# Passing a list and a scalar

# OUTPUT:

#      D:\Perl\Exs>perl funct2.pl

#      bString = bbbbb

#     nArray = 0 1 2 3 4 5 6 7 8 9 10

#     Array: = 0 1 2 3 4 5 6 7 8 9 10

#      String: = AAAA

 

$bString = "bbbbb";

@nArray  = (0..10);

 

print ("bString = $bString\n");

print ("nArray = @nArray\n");

 

 

thisSub("AAAA", (0..10));

 

sub thisSub{

    local ($para1, @array) = @_;

 

    print("Array: = @array\n");

    print("String: = $para1\n\n");

 

}

 

 

5.3 Perl Built-In Functions

 

 

Array Manipulations

 

pop(@array)

      # Return the last element of the @array, and removes the last

      # element of the array. It also reduce the size of array by 1

      # Example:

$last_element = pop(@array);

 

push(@array, $thisval)

      # add a scalar element $thisvalue to the end of the array

 

shift(@array)

      Return the first value of the @array, and reduce the size of

      @array

      @number1 = (0, 1, 2, 3);

      shift(@number1); # the result of the array is (1, 2, 3) and

                       # the value 0 is shifted out

 

unshift(@array1, @array2)

      # Add the elements of @array2 to the front of @array1

 

split(PATTERN, @STRING, LIMIT)

      # Breaks up a string based on some delimiters

 

splice(@ARRAY1, OFFSET, LENGTH, @ARRAY2)

      # Replace elements of @ARRAY1 with elements of @ARRAY2

 

 

 

Associative Array Manipulations

each(@ASSOC_ARRAY)

      # return a two-element list (key,value) from a given associative

# array

 

 

String Manipulation

 

Substring Function

substr($original_str, n, m);

# Extract a sub-string from the original string, beginning at the

# n-th character position, for m number of characters

 

Example 5-3:

$institution = 'Indiana University - Purdue University Fort Wayne';

$iu = substr($institution, 0, 18);  # Indiana University

$pu = substr($institution, 22, 28);  # Purdue University Fort Wayne

 

Number to ASCII Character Conversion

chr(NUMBER);

      $num = chr(66);  # Yields ASCII character A in the $num

 

$string = "AABB";

lc("AABB");       # Convert to lower case string and return "aabb"

lcfirst("AABB");  # Convert the first char of the string to lower case

# and return "aABB"

length("AABB");   # Return the length of the string: 4

uc("aabb");       # Return an upper case string "AABB"

ucfirst("aabb");  # Convert the first char to upper case and return

# "Aabb"

 

chomp(STRING)

chomp(ARRAY)

 

 

Local Time Function

localtime(time) returns an array of nine elements of the local time through the following calling syntax:

($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) ($sec, $min, $hour, $day, $month, $year, $day_of_week, $day_of_year, $flag_day_light_saving) = localtime(time);

 

where

the array index is ranged from 0 through 8,

$mday is the day of the month,

$mon is the month,

$wday is the day of the week is ranged from 0 = Sunday, 1 =

Monday, ..,

6 = Saturday

$yday is the the day of the year (0-364), and

$isdst is the flag for showing day light saving time

 

 

Random Number Generation

srand()      #Initialize random number generator

rand()      #Generate a random number between 0 and ?

 

 

System Pre-defined Variables

 

$ENV('REMOTE_HOST')

      # a associative array that filled with shell variables

$ENV('PATH') = '/bin:/usr/bin';

      # Setup the $PATH for program execution