PERL/C3/Including-files-or-modules/English

From Script | Spoken-Tutorial
Jump to: navigation, search

Title of script: Including files or modules in a PERL program

Author: Nirmala Venkat

Keywords: Include Module, do, use, require, PERL, PERL programming, video tutorial

Visual Cue Narration
Slide 1: Welcome to the Spoken Tutorial on Including files or modules in a PERL program
Slide 2:

Learning objectives

  • do method
  • use method
  • require method
In this tutorial we will learn to use
  • do
  • use and
  • require

methods in PERL programming.

Slide 3:

System Requirements

For this tutorial, I am using
  • Ubuntu Linux 12.04 operating system
  • Perl 5.14.2 and
  • gedit Text Editor

You can use any text editor of your choice.

Slide 4:

Pre-requisites

To follow this tutorial, you should have working knowledge of Perl programming.

If not, then go through the relevant Perl spoken tutorials on the spoken tutorial website.

Slide 5:

do file name / module name

Do Method:

These are simple ways to include the source code from other files into the current script file.

Let us understand how to use do() method.
Switch to the datetime.pl in gedit Open a new file in your text editor and name it as datetime.pl
Scroll and show the code in gedit In the datetime dot pl file, type the following code as displayed on the screen.
From here onwards, remember to press the Enter key after every command on the terminal.
Let us understand the code now.
#!/usr/local/bin/perl

$datestring = localtime();

sub msgThanks {

print("Thank you...\n");

}

The current date and time is stored in a variable dollar datestring.

Here, I have a function by name msgThanks, which returns a “Thank you” message.

Press Ctrl+S Now, press Ctrl+S to save the file.
Next let us look at another Perl program which will make use of this file datetime dot pl
Switch to the main.pl in gedit Open a new file in your text editor and name it as main dot pl
Scroll and show the code in gedit In the main dot pl file, type the following code as displayed on the screen.
Let me explain the code now.
#!/usr/bin/perl

print "Welcome to Spoken tutorials!! \n";

print "\n";

do "datetime.pl";

print ("Have a nice day! \n");

print ("Today's date: $datestring \n");

msgThanks();

Here, the first line prints the welcome message.

do() method is called with the filename from where we want to use the code.

Current date and time is stored in the $datestring variable of datetime dot pl file.

And at the end, we call the msgThanks() function from the same file.

Press Ctrl+S Now, press Ctrl+S to save the file.
Let us execute the program.
In terminal >> type perl main.pl and press Enter. Switch back to the terminal and type


perl main dot pl and press Enter

Highlight the output

Welcome to Spoken tutorials!!

Have a nice day! Today's date: Thu Aug 13 10:57:15 2015 Thank you...

Observe the output on the terminal.
<<PAUSE>>
Next we will learn how to use require method and use method in a Perl program.
Slide 6:

require and use methods

These methods are used -
  • when we have collections of subroutines
  • that can be used in multiple Perl programs.
Slide 6a:

use method:

  • use method is used only for the modules.
  • It is verified at the time of compilation
  • There is no need to give the file extension
Slide 6b:

require method:

  • require method is used for both Perl programs and modules
  • It is verified at the run time
  • One needs to give the file extension.
Slide 7:

use module name;

  • The syntax of use method is

use module name semicolon

  • Perl modules are the files which end with .pm extension.
  • Reusability of code is implemented through modules.
  • These are similar to libraries in other languages.
Now I will show a simple program with the use method to include a module in Perl code.
Switch to sum.pm file Open a new file In your text editor and name it as sum dot pm.
Scroll and show the code In the sum dot pm file, type the following code as displayed on the screen.
#!/usr/bin/perl

sub total {

my $sum = 0;

foreach my $num(@_){

$sum =$sum+ $num;

}

print "The total is : $sum\n";

}

1;

Here, I have a simple function which will calculate the sum of a given set of numbers.
Press Ctrl+S Now, press Ctrl+S to save the file
We will write another Perl script where we’ll use this sum.pm file.
Let me open the sample program app dot pl file which I have saved already
In the app dot pl file, type the following code as displayed on the screen.

Let me explain the code now.

#!/usr/bin/perl

use sum;

total(1, 7, 5, 4, 9);

total(1...10);

The first line shows the use method with the module name.

In our case, the module name is sum.

We are passing 1,7,5,4,9 as input parameters to the function total in sum dot pm file.

Again, in the next line, we are passing 1 to 10 as input parameters to the same function.

Press Ctrl+S Now, press Ctrl+S to save the file.
Let us execute the program.
In terminal >> type perl app.pl and press Enter. Switch back to the terminal and type

perl app dot pl

Highlight the output

The total is 26

The total is 55

Observe the output displayed on the terminal.
Switch to sum.pm Let us see few more options in use method.

Switch back to sum.pm in the text editor.

Add the below code

use strict; use warnings;

At the beginning of the source code, add the lines

use strict semicolon

use warnings semicolon

#!/usr/bin/perl

use strict;

use warnings;

sub total {

my $sum = 0;

foreach my $num(@_){

$sum =$sum+ $num;

}

print "The total is : $sum\n";

}

1;

use strict and use warnings are compiler flags that instruct Perl to behave in a stricter way.

These are used to avoid common programming mistakes.

use strict forces the user to declare all the variables used in the program.

If there are errors, use strict will abort the execution.

use warnings will only provide warnings but continue with the execution.

Remove my from the code

$sum =0;

Assume that we forgot to declare the variable $sum as my.

Let us now see how the same program is executed.

Press Ctrl+S Press Ctrl+S to save the file.
In terminal >> type perl app.pl and press Enter. Switch back to the terminal and type

perl app dot pl

Highlight the output

Global symbol "$sum" requires explicit package name at sum.pm line 8.

Global symbol "$sum" requires explicit package name at sum.pm line 9.

Global symbol "$sum" requires explicit package name at sum.pm line 10.

Compilation failed in require at app.pl line 5.

BEGIN failed--compilation aborted at app.pl line 5.

We can see that the program is aborted without executing the result.

The first set of lines displayed on the terminal are error messages generated by “use strict”.

The last two are the abort messages.

So, this is how the use method options work.
Next let us see a Perl program where we use the require method.
Switch to commonfunctions.pl in gedit Let me open the sample program commonfunctions.pl which I have already saved.
Scroll and show the code Type the following code as displayed on the screen in your commonfunctions dot pl file.

Let us understand the code now.

sub square() {

my ($number) = @_;

return ($number * $number);

}

sub square_root() {

my ($number) = @_;

return (sqrt($number));

}

sub random_number() {

my ($number) = @_;

return (rand($number));

}

# generate a random number in perl between a range of numbers

sub random_range() {

my ($lrange, $urange) = @_;

return int(rand($urange-$lrange))+ $lrange;

}

1;

Here we can see a collection of commonly used functions.

The first function square() returns the square of a number.

The second function square underscore root() returns the square root of a given number.

Next function random underscore number() generates a random number.

The last function random underscore range() generates a random number between a lower range and upper range of numbers.

Note that we need the 1 semicolon at the end of the file.

This is because Perl needs the last expression in the file to return a true value.

Press Ctrl+S Now, press Ctrl+S to save the file.
Next we will write a Perl program in which we’ll call these subroutines using require method.
Switch to callprogram.pl Let me open the sample program callprogram dot pl which I have already saved.
Type the following code as displayed on the screen in your file.

Let me explain the code now.

#!/usr/bin/perl

use strict;

use warnings;

require 'commonfunctions.pl';

print "1.Square of a number \n";

print "2.Square root of a number \n";

print "3.Random number in the given range\n";

print "4.Quit \n";

print "Enter the Option: ";

my $option = <>;

if ($option == 1)

{

# Find a square of a number

print "Enter a number: ";

my $number = <>;

print "Square of $number is: " .square($number) . "\n";

}

elsif ($option == 2)

{

# Find a square root of a number

print "Enter a number: ";

my $number1 = <>;

print "Squareroot of $number1 is:" .square_root($number1) . "\n";

}

elsif ($option == 3)

{

# Find a random number in the given range

print "Enter a lower range: ";

my $lower = <>;

print "Enter a upper range:";

my $upper = <>;

print "Random number in the given range is: " .random_range($lower,$upper) . "\n";

}

elsif ($option == 4)

{ exit;

}

else { print "Incorrect option. Exiting the program \n";

}

require reads the commonfunctions.pl file containing Perl code and compiles it.

This program gives 4 options to the user.

The user has to choose one option at a time.

One is to find the square of a number.

Two is for square root of a number.

Three is for a random number in the given range.

Four is to quit the program.

If option one is typed, it will ask the user to enter a number.

The value is stored in $number.

This is passed to the function square in commonfunctions.pl file.

The function returns the square of a number.

The print statement prints the square of a number as output.

If option two is typed, the square root of a number is displayed as output.

The execution is followed as explained in the previous function square.

If option three is typed, a random number is displayed as output in the given range.

Else if option is four, the program exits.

If any option other than the ones specified is given, the print statement says “Incorrect option”.

Note that in this program we have called only three functions out of four from commonfunctions.pl.

Press Ctrl+S Now, press Ctrl+S to save the file
Let us execute the program.
In terminal >> type perl callprogram.pl and press Enter. Switch back to the terminal and type

perl callprogram dot pl

Highlight the output

1.Square of a number

2.Square root of a number

3.Random number in the given range

4.Quit

Enter the Option: 2

Enter a number: 169

Square root of 169 is: 13

Observe the output
I'll execute the program once again with a different option.
In terminal >> type perl callprogram.pl and press Enter. Type perl callprogram dot pl
Highlight the output

1.Square of a number

2.Square root of a number

3.Random number in the given range

4.Quit

Enter the Option: 3 Enter the Option as 3.
Enter a lower range: 50

Enter a upper range: 99

Enter a lower range as 50.

Enter a upper range as 99.

Random number in the given range is: 71 We can see the random number is generated in the given range of numbers.
Try other options on your own.
This brings us to the end of this tutorial. Let us summarise.
Slide 8:

Summary

In this tutorial we learnt to use
  • do
  • use
  • require

methods in PERL programming.

Note: "use Module" is recommended over "require Module", because it determines module availability at compile time.

Slide 9:

Assignment

Here is an assignment for you.
  1. Write a Perl program reminder.pl where you will write a letter to the participants.
  2. Prompt the user to enter To and From name
  3. Call the subroutines from Letter.pm using ‘use’ method.
  4. Write the below functions in Letter.pm file.
  • LetterDate() function returns the current date and time
  • To() function returns the name of the participants
  • From() function returns the sender name
  • Lettermsg() function returns the content of the letter
  • Thanksmsg() function returns thanks and regards.
Slide 10:

Output

To: Mr. Ram, 23 Gandhi Nagar, Mumbai-400034.

From: Vikash

Date: Thu Aug 13 11:25:29 2015

Greetings!!

This is to remind you that your registration fees of Rs. 500.00 is pending.

If you have not yet made the payment, kindly do so immediately.

Thanks and regards,

Vikash.

The output should be displayed as shown here.
Slide 11:

About Spoken Tutorial project


The video at the following link summarises the Spoken Tutorial project.

Please download and watch it

Slide 12:

Spoken Tutorial workshops

The Spoken Tutorial Project Team
  • conducts workshops using spoken tutorials and
  • gives certificates on passing online tests.

For more details, please write to us.

Slide 13:

Acknowledgement

Spoken Tutorial project is funded by NMEICT, MHRD, Government of India.

More information on this mission is available at

this link.

This is Nirmala Venkat from IIT Bombay, signing off. Thanks for watching.

Contributors and Content Editors

Nancyvarkey, Nirmala Venkat, PoojaMoolya