PERL/C3/Special-Variables-in-PERL/English

From Script | Spoken-Tutorial
Revision as of 18:05, 14 July 2015 by Nancyvarkey (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Title of script: Special Variables in PERL Author: Nirmala Venkat Keywords: Special Variables, Global special variables, Special command line variables, Global special constants, gedit, video tutorial

Visual Cue
Narration
Slide 1: Welcome to the Spoken Tutorial on special variables in Perl.
Slide 2:

Learning objectives

In this tutorial we will learn about
  • Global special variables
  • Special command line variables
  • Global special constants
Slide 3:

System Requirements

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

You can use any text editor of your choice.

Slide 4:

Pre-requisites

As a prerequisite, 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: What are special variables?
  • Special variables are predefined variables that have a special meaning in Perl.
  • These do not need to be initialised before use.
  • These are used to hold the results of searches, environment variables and flags to control debugging.
First, we will learn about Global special variables.
Slide 6: $_ : (Dollar Underscore)

This is a widely used special variable.

$_ - Dollar Underscore is the default parameter for lot of functions and pattern-searching strings.

Let us understand the usage of $_ variable using a sample program.
Switch to the Terminal and type

gedit special.pl &

I will open the special dot pl file which I have already created.

Go to the terminal and type gedit special.pl ampersand and press Enter.

Point the cursor special.pl special.pl file is now open in gedit.

Type the code as displayed on the screen.

Let me explain the code now.

Highlight in gedit

#Example1

#!/usr/bin/perl

foreach my $color ('Red','Green','Blue') {

print “$color \n”; }

foreach ('Red','Green','Blue') {

print “$_ \n”; }

There are 2 foreach loops here.

Both these foreach loops will execute the same result.


In each iteration of the loop, the current string is placed in $_.

And it is used by the print statement, by default.


$_ saves the use of one extra variable $color.

Press Ctrl+S Press Ctrl+S to save the file.

Then switch to the terminal and execute the Perl script by typing

perl special dot pl and press Enter.

Highlight the output Here both foreach loops give the same output.
Now, let us see another example to demonstrate how $_ variable is implicit.

Go back to the special dot pl file.

#Example2

#!/usr/bin/perl

open(DATA, "<first.txt") or die "Couldn't open file first.txt, $!";

while(<DATA>){

print "$_"; }

Type the piece of code shown on the screen.

This program reads a text file first.txt line by line.

Then it loops through the DATA file, till all lines are read.

print $_ variable prints the contents of the current line from the first.txt file.

In the 'while' loop, the use of $_ is implicit.

We will see more about this in future tutorials.
Slide: 7 At the rate underscore is the special variable used to store subroutine parameters.

Arguments for a subroutine are stored in this array variable.

Array operations like pop/shift can be done on this variable, as we do in normal arrays.

Switch to the Terminal and type

gedit special.pl &

I will show an example for this.

Let us switch back to special dot pl file once again.

Point the cursor special.pl Type the code as displayed on the screen.
sub max {

my ($a, $b) = @_;

if ($a > $b) {

return $a;

}

return $b;

}

print max(23, 42);

This program will return the maximum value between two numbers.

@_ - At the rate underscore is a local array which stores the two arguments dollar a comma dollar b.

That is, it is stored under

  • dollar underscore index of zero
  • and dollar underscore index of one
  • i.e $_[0] and $_[1]

The print statement prints the maximum of the two given numbers.

Press Ctrl+S Press Ctrl+S to save the file.
Switch to terminal

perl special dot pl

Switch to the terminal and execute the Perl script by typing

perl special dot pl and press Enter.

Highlight the output The maximum value is displayed as output.

Let’s move on.

Slide:8 Environment variables are represented by percentage followed by capital ENV.


Environment variables contain a copy of the current environment variables, such as the following.

Let us understand %ENV variable using a sample program.
We will switch back to the special dot pl file.
Example:

foreach (keys %ENV) {

print $_, "::", $ENV{$_}, "\n";

}

Type the following code as displayed on the screen.
Press Ctrl+S to save the file.

Switch to the terminal and execute the Perl script.


Type perl special dot pl and press Enter.

Highlight the output We can see the current environment details such as
  • PWD (present working directory), username, language etc.
Next we will see about another special variable dollar zero
Slide:9

Example:

print $0, "\n";

The special variable dollar zero ($0) contains name of the current Perl program that is being executed.

This is generally used for logging purpose.

For example: I have a file named First.pl within which I am using $0 variable as shown here.

On executing, it will print the filename First.pl.

Slide:10 Perl has a built-in function called sort that sorts an array.

A comparison function will compare its parameters using the numerical comparison operator.

This operator is represented by lesser than equal to greater than symbols, as shown here.

Let us see an example for this.
Switch to the Terminal and type

gedit sort.pl &

Open the terminal and type

gedit sort.pl ampersand and press Enter.

Point the cursor sort.pl sort.pl file is now open in gedit Text Editor.

Type the following code as displayed on the screen.

#!/usr/bin/perl

# sort numerically ascending

my @numbers = (14, 6, 12, 3, 28);

my @sorted_numbers = sort {$a<=>$b} @numbers;

print @sorted_numbers;

Let me explain the code.

The first line declares an array of numbers.

The numerical comparison operator will compare the two values as numbers.

Dollar a and dollar b are special package local variables in which the values to be compared are loaded.

And this sort function will sort the numbers in ascending order.

Let us now save and execute the program.
Switch back to the terminal and type,

perl sort.pl and press Enter.

Highlight

Output

We can see that the numbers are sorted in ascending order.
Slide: 11

Example:

open FH, "<", "hello.txt" or die "Cannot open file for reading : $!";

Let’s see another special variable dollar exclamation.

dollar exclamation if used in string context, returns the system error string. Here is an example of its usage.

If the file hello.txt doesn't exist, it will print the error message,like:

Cannot open file for reading : No such file or directory.

Slide: 12

Example:

my $result= eval { $x/ $y };

print “ could not divide $@" if $@;

Let’s now look at another special variable namely, dollar at the rate.

This is another widely used variable.

It returns an error message, returned from eval or require command.

This example will print: could not divide Illegal division by zero.

Slide:13

Example:

print “$$\n”;

dollar dollar is yet another special variable.

This holds the process ID of the Perl interpreter running this script.

Special command line variables PAUSE
Slide:14

Example:

while(<>) {

print "$_ \n"; }

The diamond operator is used to read every line, from the files specified on the command line.
Let us see an example for this.
Switch to the Terminal and type

gedit commandline.pl &

Open the terminal and type gedit commandline.pl ampersand and press Enter.
Point the cursor commandline.pl commandline.pl file is now open in gedit.
Type the code as displayed on the screen.
Save the file.
Switch to sample.txt in gedit itself. Let me show you the text that I have in a file named sample.txt file.
On the terminal type

perl commandline.pl sample.txt

Now, run the program from the command line by typing: perl commandline.pl space sample.txt and press Enter.
Highlight the output This is the text we had in sample.txt file.

If no files are specified, it reads from the standard input i.e. from the keyboard. <<PAUSE>>

Slide: 15

Example:

foreach (@ARGV) {

print;

print "\n"; }

Perl has an array at the rate capital A R G V special variable.

This holds all the values from the command line.

When using array at the rate capital A R G V, there is no need to declare the variables.


The values from the command line are automatically placed in this variable.

Global Special Constants Let’s now move on to Global Special Constants.
Slide:16 underscore underscore E N D (in capital letters)underscore underscore.

…. indicates the logical end of the program.

Any text following this special variable is ignored after this statement.

underscore underscore FILE (in capital letters) underscore underscore.

...represents the filename of the program at the point where it is used.

underscore underscore LINE (in capital letters) underscore underscore.

...represents the current line number

underscore underscore PACKAGE (in capital letters) underscore underscore.

...represents the current package name at compile time, or undefined if there is no current package.

We will see a sample program on how Global Special Constants are used.
Switch to the Terminal and type

gedit specialconstant.pl &

Open the terminal and type

gedit specialconstant.pl ampersand and press Enter.

Point the cursor specialconstant.pl specialconstant.pl file is now open in gedit.

Type the following code as displayed on the screen.

Let me explain the code now.

#!/usr/bin/perl

# This is second package

package second;

our $i = 20;

print "Package Name : " , __PACKAGE__ , " $i\n"; #print 20

Print “File name:”, __FILE__, “Line No:”, __LINE__, “\n”;

The special literals __PACKAGE__ , __FILE__, __LINE__ represent the
  • package name,
  • current filename and
  • line number

respectively at that point in the program.

Let us execute the program.
Switch to the Terminal and type

perl specialconstant.pl

Switch back to the terminal and type:

perl specialconstant.pl and press Enter.

Highlight the output We can see the current package name, filename and line number of our program.
Slide 17:

Summary

This brings us to the end of this tutorial. Let us summarise.

In this tutorial, we learnt about some commonly used special variables in Perl.

Slide 18:

Assignment

As an assignment do the following.

Write a Perl script to sort the following array of numbers in ascending and descending order.

  1. my @numbers = ( 22, 88, 33, 55, 11);
  2. Note: For descending order, use the below code for comparison.
    sort {$b<=>$a} @numbers;
  3. Print the sorted result using ‘while loop’ and special variable $_.
  4. Save and execute the program.
  5. Now check the result.
Slide 18:

About Spoken Tutorial project

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

Please download and watch it

Slide 19:

About workshops

The Spoken Tutorial Project Team

conducts workshops and gives certificates on passing online tests.

For more details, please write to us.
Slide 20:

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