onlyforbopi
10/3/2019 - 11:20 AM

Perl.Reference

#perl #reference #quickreference #syntax

# How to run
# Perl borrows syntax and concepts from many languages: awk, sed, C, Bourne Shell, Smalltalk, Lisp and even English. However, there are some definite differences between the languages. This chapter is designd to quickly get you up to speed on the syntax that is expected in Perl.

# A Perl program consists of a sequence of declarations and statements, which run from the top to the bottom. Loops, subroutines, and other control structures allow you to jump around within the code. Every simple statement must end with a semicolon (;).

# Perl is a free-form language: you can format and indent it however you like. Whitespace serves mostly to separate tokens, unlike languages like Python where it is an important part of the syntax, or Fortran where it is immaterial.

# First Perl Program
# Interactive Mode Programming
# You can use Perl interpreter with -e option at command line, which lets you execute Perl statements from the command line. Let's try something at $ prompt as follows −

$perl -e 'print "Hello World\n"'



# This execution will produce the following result −
# Hello, world


###
# Script Mode Programming
# Assuming you are already on $ prompt, let's open a text file hello.pl using vi or vim editor and put the following lines inside your file.


#!/usr/bin/perl
# This will print "Hello, World"
print "Hello, world\n";


# Here /usr/bin/perl is actual the perl interpreter binary. Before you execute your script, be sure to change the mode of the script file and give execution priviledge, generally a setting of 0755 works perfectly and finally you execute the above script as follows −

$chmod 0755 hello.pl
$./hello.pl

# This execution will produce the following result −
# Hello, world

# You can use parentheses for functions arguments or omit them according to your personal taste. They are only required occasionally to clarify the issues of precedence. Following two statements produce the same result.

print("Hello, world\n");
print "Hello, world\n";

###
# Perl File Extension
# A Perl script can be created inside of any normal simple-text editor program. There are several programs available for every type of platform. There are many programs designd for programmers available for download on the web.

# As a Perl convention, a Perl file must be saved with a .pl or .PL file extension in order to be recognized as a functioning Perl script. File names can contain numbers, symbols, and letters but must not contain a space. Use an underscore (_) in places of spaces.


###
# Comments in Perl
# Comments in any programming language are friends of developers. Comments can be used to make program user friendly and they are simply skipped by the interpreter without impacting the code functionality. For example, in the above program, a line starting with hash # is a comment.



###
# COMMENTS
# Simply saying comments in Perl start with a hash symbol and run to the end of the line −
# This is a comment in perl
# Lines starting with = are interpreted as the start of a section of embedded documentation (pod), and all subsequent lines until the next =cut are ignored by the compiler. Following is the example −

#!/usr/bin/perl

# This is a single line comment
print "Hello, world\n";

=begin comment
This is all part of multiline comment.
You can use as many lines as you like
These comments will be ignored by the 
compiler until the next =cut is encountered.
=cut

#This will produce the following result −
#Hello, world

###
#Whitespaces in Perl
#A Perl program does not care about whitespaces. Following program works perfectly fine −

#!/usr/bin/perl

print       "Hello, world\n";

#But if spaces are inside the quoted strings, then they would be printed as is. For example −


#!/usr/bin/perl

# This would print with a line break in the middle
print "Hello
          world\n";

		  
#This will produce the following result −
#Hello
#          world


#All types of whitespace like spaces, tabs, newlines, etc. are equivalent for the interpreter when they are used outside of the quotes. A line containing only whitespace, possibly with a comment, is known as a blank line, and Perl totally ignores it.


####
#Single and Double Quotes in Perl
#You can use double quotes or single quotes around literal strings as follows −

Live Demo
#!/usr/bin/perl

print "Hello, world\n";
print 'Hello, world\n';
This will produce the following result −

Hello, world
Hello, world\n$


# There is an important difference in single and double quotes. Only double quotes interpolate variables and special characters such as newlines \n, whereas single quote does not interpolate any variable or special character. Check below example where we are using $a as a variable to store a value and later printing that value −


#!/usr/bin/perl

$a = 10;
print "Value of a = $a\n";
print 'Value of a = $a\n';
This will produce the following result −

Value of a = 10
Value of a = $a\n$

###
#"Here" Documents
# You can store or print multiline text with a great comfort. Even you can make use of variables inside the "here" document. Below is a simple syntax, check carefully there must be no space between the << and the identifier.

# An identifier may be either a bare word or some quoted text like we used EOF below. If identifier is quoted, the type of quote you use determines the treatment of the text inside the here docoment, just as in regular quoting. An unquoted identifier works like double quotes.


#!/usr/bin/perl

$a = 10;
$var = <<"EOF";
This is the syntax for here document and it will continue
until it encounters a EOF in the first line.
This is case of double quote so variable value will be 
interpolated. For example value of a = $a
EOF
print "$var\n";

$var = <<'EOF';
This is case of single quote so variable value will be 
interpolated. For example value of a = $a
EOF
print "$var\n";


# This will produce the following result −
# This is the syntax for here document and it will continue
# until it encounters a EOF in the first line.
# This is case of double quote so variable value will be
# interpolated. For example value of a = 10

# This is case of single quote so variable value will be
# interpolated. For example value of a = $a

###
#Escaping Characters
# Perl uses the backslash (\) character to escape any type of character that might interfere with our code. Let's take one example where we want to print double quote and $ sign −


#!/usr/bin/perl

$result = "This is \"number\"";
print "$result\n";
print "\$result\n";


#This will produce the following result −
#This is "number"
#$result


###
#Perl Identifiers
# A Perl identifier is a name used to identify a variable, function, class, module, or other object. A Perl variable name starts with either $, @ or % followed by zero or more letters, underscores, and digits (0 to 9).

# Perl does not allow punctuation characters such as @, $, and % within identifiers. Perl is a case sensitive programming language. Thus $Manpower and $manpower are two different identifiers in Perl.

# Perl is a loosely typed language and there is no need to specify a type for your data while using in your program. The Perl interpreter will choose the type based on the context of the data itself.

# Perl has three basic data types: scalars, arrays of scalars, and hashes of scalars, also known as associative arrays. Here is a little detail about these data types.

# Sr.No.	Types & Description
# 1	
# Scalar

# Scalars are simple variables. They are preceded by a dollar sign ($). A scalar is either a number, a string, or a reference. A reference is actually an address of a variable, which we will see in the upcoming chapters.

# 2	
# Arrays

# Arrays are ordered lists of scalars that you access with a numeric index, which starts with 0. They are preceded by an "at" sign (@).

# 3	
# Hashes

# Hashes are unordered sets of keyvalue pairs that you access using the keys as subscripts. They are preceded by a percent sign (%).

# Numeric Literals
# Perl stores all the numbers internally as either signed integers or double-precision floating-point values. Numeric literals are specified in any of the following floating-point or integer formats −

# Type	Value
# Integer	1234
# Negative integer	-100
# Floating point	2000
# Scientific notation	16.12E14
# Hexadecimal	0xffff
# Octal	0577
# String Literals
# Strings are sequences of characters. They are usually alphanumeric values delimited by either single (') or double (") quotes. They work much like UNIX shell quotes where you can use single quoted strings and double quoted strings.

# Double-quoted string literals allow variable interpolation, and single-quoted strings are not. There are certain characters when they are proceeded by a back slash, have special meaning and they are used to represent like newline (\n) or tab (\t).

# You can embed newlines or any of the following Escape sequences directly in your double quoted strings −

# Escape sequence	Meaning
# \\	Backslash
# \'	Single quote
# \"	Double quote
# \a	Alert or bell
# \b	Backspace
# \f	Form feed
# \n	Newline
# \r	Carriage return
# \t	Horizontal tab
# \v	Vertical tab
# \0nn	Creates Octal formatted numbers
# \xnn	Creates Hexideciamal formatted numbers
# \cX	Controls characters, x may be any character
# \u	Forces next character to uppercase
# \l	Forces next character to lowercase
# \U	Forces all following characters to uppercase
# \L	Forces all following characters to lowercase
# \Q	Backslash all following non-alphanumeric characters
# \E	End \U, \L, or \Q

#!/usr/bin/perl

# This is case of interpolation.
$str = "Welcome to \ntutorialspoint.com!";
print "$str\n";

# This is case of non-interpolation.
$str = 'Welcome to \ntutorialspoint.com!';
print "$str\n";

# Only W will become upper case.
$str = "\uwelcome to tutorialspoint.com!";
print "$str\n";

# Whole line will become capital.
$str = "\UWelcome to tutorialspoint.com!";
print "$str\n";

# A portion of line will become capital.
$str = "Welcome to \Ututorialspoint\E.com!"; 
print "$str\n";

# Backsalash non alpha-numeric including spaces.
$str = "\QWelcome to tutorialspoint's family";
print "$str\n";

# Variables are the reserved memory locations to store values. This means that when you create a variable you reserve some space in memory.

# Based on the data type of a variable, the interpreter allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals, or strings in these variables.

# We have learnt that Perl has the following three basic data types −

# Scalars
# Arrays
# Hashes

# Accordingly, we are going to use three types of variables in Perl. A scalar variable will precede by a dollar sign ($) and it can store either a number, a string, or a reference. An array variable will precede by sign @ and it will store ordered lists of scalars. Finaly, the Hash variable will precede by sign % and will be used to store sets of key/value pairs.

# Perl maintains every variable type in a separate namespace. So you can, without fear of conflict, use the same name for a scalar variable, an array, or a hash. This means that $foo and @foo are two different variables.

# Creating Variables
# Perl variables do not have to be explicitly declared to reserve memory space. The declaration happens automatically when you assign a value to a variable. The equal sign (=) is used to assign values to variables. Keep a note that this is mandatory to declare a variable before we use it if we use use strict statement in our program.
# The operand to the left of the = operator is the name of the variable, and the operand to the right of the = operator is the value stored in the variable. For example −

$age = 25;             # An integer assignment
$name = "John Paul";   # A string 
$salary = 1445.50;     # A floating point


# Scalar Variables
# A scalar is a single unit of data. That data might be an integer number, floating point,a character, a string, a paragraph, or an entire web page. Simply saying it could be anything, but only a single thing.

# Here is a simple example of using scalar variables −


#!/usr/bin/perl

$age = 25;             # An integer assignment
$name = "John Paul";   # A string 
$salary = 1445.50;     # A floating point

print "Age = $age\n";
print "Name = $name\n";
print "Salary = $salary\n";



# Array Variables
# An array is a variable that stores an ordered list of scalar values. Array variables are preceded by an "at" (@) sign. To refer to a single element of an array, you will use the dollar sign ($) with the variable name followed by the index of the element in square brackets.


#!/usr/bin/perl

@ages = (25, 30, 40);             
@names = ("John Paul", "Lisa", "Kumar");

print "\$ages[0] = $ages[0]\n";
print "\$ages[1] = $ages[1]\n";
print "\$ages[2] = $ages[2]\n";
print "\$names[0] = $names[0]\n";
print "\$names[1] = $names[1]\n";
print "\$names[2] = $names[2]\n";


$ages[0] = 25
$ages[1] = 30
$ages[2] = 40
$names[0] = John Paul
$names[1] = Lisa
$names[2] = Kumar

#Hash Variables
# A hash is a set of key/value pairs. Hash variables are preceded by a percent (%) sign. To refer to a single element of a hash, you will use the hash variable name followed by the "key" associated with the value in curly brackets.


#!/usr/bin/perl

%data = ('John Paul', 45, 'Lisa', 30, 'Kumar', 40);

print "\$data{'John Paul'} = $data{'John Paul'}\n";
print "\$data{'Lisa'} = $data{'Lisa'}\n";
print "\$data{'Kumar'} = $data{'Kumar'}\n";

Variable Context
Perl treats same variable differently based on Context, i.e., situation where a variable is being used. Let's check the following example −

#!/usr/bin/perl

@names = ('John Paul', 'Lisa', 'Kumar');

@copy = @names;
$size = @names;

print "Given names are : @copy\n";
print "Number of names are : $size\n";

# This will produce the following result −

# Given names are : John Paul Lisa Kumar
# Number of names are : 3
# Here @names is an array, which has been used in two different contexts. First we copied it into anyother array, i.e., list, so it returned all the elements assuming that context is list context. Next we used the same array and tried to store this array in a scalar, so in this case it returned just the number of elements in this array assuming that context is scalar context. Following table lists down the various contexts −

# Scalar
# Assignment to a scalar variable evaluates the right-hand side in a scalar context.
	
# List
# Assignment to an array or a hash evaluates the right-hand side in a list context.

# Boolean
# Boolean context is simply any place where an expression is being evaluated to see whether it's true or false.
	
# Void
# This context not only doesn't care what the return value is, it doesn't even want a return value.

# A scalar is a single unit of data. That data might be an integer number, floating point, a character, a string, a paragraph, or an entire web page.


#!/usr/bin/perl

$age = 25;             # An integer assignment
$name = "John Paul";   # A string 
$salary = 1445.50;     # A floating point

print "Age = $age\n";
print "Name = $name\n";
print "Salary = $salary\n";

#A scalar is most often either a number or a string. Following example demonstrates the usage of various types of numeric scalars −


#!/usr/bin/perl
$integer = 200;
$negative = -300;
$floating = 200.340;
$bigfloat = -1.2E-23;

# 377 octal, same as 255 decimal
$octal = 0377;

# FF hex, also 255 decimal
$hexa = 0xff;

print "integer = $integer\n";
print "negative = $negative\n";
print "floating = $floating\n";
print "bigfloat = $bigfloat\n";
print "octal = $octal\n";
print "hexa = $hexa\n";

# STRING SCALARS
#!/usr/bin/perl

$var = "This is string scalar!";
$quote = 'I m inside single quote - $var';
$double = "This is inside single quote - $var";

$escape = "This example of escape -\tHello, World!";

print "var = $var\n";
print "quote = $quote\n";
print "double = $double\n";
print "escape = $escape\n";

#Scalar Operations
#You will see a detail of various operators available in Perl in a separate chapter, #but here we are going to list down few numeric and string operations.


#!/usr/bin/perl

$str = "hello" . "world";       # Concatenates strings.
$num = 5 + 10;                  # adds two numbers.
$mul = 4 * 5;                   # multiplies two numbers.
$mix = $str . $num;             # concatenates string and number.

print "str = $str\n";
print "num = $num\n";
print "mul = $mul\n";
print "mix = $mix\n";

###
#Multiline Strings
#If you want to introduce multiline strings into your programs, you can use the standard single quotes as below −

#!/usr/bin/perl

$string = 'This is
a multiline
string';

print "$string\n";

#You can use "here" document syntax as well to store or print multilines as below −

#!/usr/bin/perl

print <<EOF;
This is
a multiline
string
EOF


# V-Strings
# A literal of the form v1.20.300.4000 is parsed as a string composed of characters with the specified ordinals. This form is known as v-strings.

# A v-string provides an alternative and more readable way to construct strings, rather than use the somewhat less readable interpolation form "\x{1}\x{14}\x{12c}\x{fa0}".

# They are any literal that begins with a v and is followed by one or more dot-separated elements. For example −

#!/usr/bin/perl

$smile  = v9786;
$foo    = v102.111.111;
$martin = v77.97.114.116.105.110; 

print "smile = $smile\n";
print "foo = $foo\n";
print "martin = $martin\n";

# This will also produce the same result −

# smile = ☺
# foo = foo
# martin = Martin
# Wide character in print at main.pl line 7.


# Special Literals
# So far you must have a feeling about string scalars and its concatenation and interpolation opration. So let me tell you about three special literals __FILE__, __LINE__, and __PACKAGE__ represent the current filename, line number, and package name at that point in your program.

# They may be used only as separate tokens and will not be interpolated into strings. Check the below example −

#!/usr/bin/perl

print "File name ". __FILE__ . "\n";
print "Line Number " . __LINE__ ."\n";
print "Package " . __PACKAGE__ ."\n";

# they can not be interpolated
print "__FILE__ __LINE__ __PACKAGE__\n";



# ARRAYS
# An array is a variable that stores an ordered list of scalar values. Array variables are preceded by an "at" (@) sign. To refer to a single element of an array, you will use the dollar sign ($) with the variable name followed by the index of the element in square brackets.


#!/usr/bin/perl

@ages = (25, 30, 40);             
@names = ("John Paul", "Lisa", "Kumar");

print "\$ages[0] = $ages[0]\n";
print "\$ages[1] = $ages[1]\n";
print "\$ages[2] = $ages[2]\n";
print "\$names[0] = $names[0]\n";
print "\$names[1] = $names[1]\n";
print "\$names[2] = $names[2]\n";


# Array Creation
# Array variables are prefixed with the @ sign and are populated using either parentheses or the qw operator. For example −

# @array = (1, 2, 'Hello');
# @array = qw/This is an array/;
# The second line uses the qw// operator, which returns a list of strings, separating the delimited string by white space. In this example, this leads to a four-element array; the first element is 'this' and last (fourth) is 'array'. This means that you can use different lines as follows −

# @days = qw/Monday
# Tuesday
# ...
# Sunday/;
# You can also populate an array by assigning each value individually as follows −

# $array[0] = 'Monday';
# ...
# $array[6] = 'Sunday';
# Accessing Array Elements
# When accessing individual elements from an array, you must prefix the variable with a dollar sign ($) and then append the element index within the square brackets after the name of the variable. For example −


#!/usr/bin/perl

@days = qw/Mon Tue Wed Thu Fri Sat Sun/;

print "$days[0]\n";
print "$days[1]\n";
print "$days[2]\n";
print "$days[6]\n";
print "$days[-1]\n";
print "$days[-7]\n";

print $days[-1]; # outputs Sun
print $days[-7]; # outputs Mon


# Sequential Number Arrays
# Perl offers a shortcut for sequential numbers and letters. Rather than typing out each element when counting to 100 for example, we can do something like as follows −

#!/usr/bin/perl

@var_10 = (1..10);
@var_20 = (10..20);
@var_abc = (a..z);

print "@var_10\n";   # Prints number from 1 to 10
print "@var_20\n";   # Prints number from 10 to 20
print "@var_abc\n";  # Prints number from a to z

# Here double dot (..) is called range operator. This will produce the following result −

# 1 2 3 4 5 6 7 8 9 10
# 10 11 12 13 14 15 16 17 18 19 20
# a b c d e f g h i j k l m n o p q r s t u v w x y z



# Array Size
# The size of an array can be determined using the scalar context on the array - the returned value will be the number of elements in the array −

@array = (1,2,3);
print "Size: ",scalar @array,"\n";
# The value returned will always be the physical size of the array, not the number of valid elements. You can demonstrate this, and the difference between scalar @array and $#array, using this fragment is as follows −


#!/usr/bin/perl

@array = (1,2,3);
$array[50] = 4;

$size = @array;
$max_index = $#array;

print "Size:  $size\n";
print "Max Index: $max_index\n";


# Adding and Removing Elements in Array
# Perl provides a number of useful functions to add and remove elements in an array. You may have a question what is a function? So far you have used print function to print various values. Similarly there are various other functions or sometime called sub-routines, which can be used for various other functionalities.

# Sr.No.	Types & Description
# 1	
# push @ARRAY, LIST

# Pushes the values of the list onto the end of the array.

# 2	
# pop @ARRAY

# Pops off and returns the last value of the array.

# 3	
# shift @ARRAY

# Shifts the first value of the array off and returns it, shortening the array by 1 and moving everything down.

# 4	
# unshift @ARRAY, LIST

# Prepends list to the front of the array, and returns the number of elements in the new array.

Live Demo
#!/usr/bin/perl

# create a simple array
@coins = ("Quarter","Dime","Nickel");
print "1. \@coins  = @coins\n";

# add one element at the end of the array
push(@coins, "Penny");
print "2. \@coins  = @coins\n";

# add one element at the beginning of the array
unshift(@coins, "Dollar");
print "3. \@coins  = @coins\n";

# remove one element from the last of the array.
pop(@coins);
print "4. \@coins  = @coins\n";

# remove one element from the beginning of the array.
shift(@coins);
print "5. \@coins  = @coins\n";


# Slicing Array Elements
# You can also extract a "slice" from an array - that is, you can select more than one item from an array in order to produce another array.


#!/usr/bin/perl

@days = qw/Mon Tue Wed Thu Fri Sat Sun/;

@weekdays = @days[3,4,5];

print "@weekdays\n";

# ARRAY SLICING
#!/usr/bin/perl

@days = qw/Mon Tue Wed Thu Fri Sat Sun/;

@weekdays = @days[3..5];

print "@weekdays\n";


# splice @ARRAY, OFFSET [ , LENGTH [ , LIST ] ]
# This function will remove the elements of @ARRAY designated by OFFSET and LENGTH, and replaces them with LIST, if specified. Finally, it returns the elements removed from the array. Following is the example −


#!/usr/bin/perl

@nums = (1..20);
print "Before - @nums\n";

splice(@nums, 5, 5, 21..25); 
print "After - @nums\n";

# Transform Strings to Arrays
# Let's look into one more function called split(), which has the following syntax −

# split [ PATTERN [ , EXPR [ , LIMIT ] ] ]
# This function splits a string into an array of strings, and returns it. If LIMIT is specified, splits into at most that number of fields. If PATTERN is omitted, splits on whitespace. Following is the example −

Live Demo
#!/usr/bin/perl

# define Strings
$var_string = "Rain-Drops-On-Roses-And-Whiskers-On-Kittens";
$var_names = "Larry,David,Roger,Ken,Michael,Tom";

# transform above strings into arrays.
@string = split('-', $var_string);
@names  = split(',', $var_names);

print "$string[3]\n";  # This will print Roses
print "$names[4]\n";   # This will print Michael


# Transform Arrays to Strings
# We can use the join() function to rejoin the array elements and form one long scalar string. This function has the following syntax −

# join EXPR, LIST
# This function joins the separate strings of LIST into a single string with fields separated by the value of EXPR, and returns the string. Following is the example −


#!/usr/bin/perl

# define Strings
$var_string = "Rain-Drops-On-Roses-And-Whiskers-On-Kittens";
$var_names = "Larry,David,Roger,Ken,Michael,Tom";

# transform above strings into arrays.
@string = split('-', $var_string);
@names  = split(',', $var_names);

$string1 = join( '-', @string );
$string2 = join( ',', @names );

print "$string1\n";
print "$string2\n";





# Sorting Arrays
# The sort() function sorts each element of an array according to the ASCII Numeric standards. This function has the following syntax −

# sort [ SUBROUTINE ] LIST
# This function sorts the LIST and returns the sorted array value. If SUBROUTINE is specified then specified logic inside the SUBTROUTINE is applied while sorting the elements.


#!/usr/bin/perl

# define an array
@foods = qw(pizza steak chicken burgers);
print "Before: @foods\n";

# sort this array
@foods = sort(@foods);
print "After: @foods\n";



# The $[ Special Variable
# So far you have seen simple variable we defined in our programs and used them to store and print scalar and array values. Perl provides numerous special variables, which have their predefined meaning.

# We have a special variable, which is written as $[. This special variable is a scalar containing the first index of all arrays. Because Perl arrays have zero-based indexing, $[ will almost always be 0. But if you set $[ to 1 then all your arrays will use on-based indexing. It is recommended not to use any other indexing other than zero. However, let's take one example to show the usage of $[ variable −

Live Demo
#!/usr/bin/perl

# define an array
@foods = qw(pizza steak chicken burgers);
print "Foods: @foods\n";

# Let's reset first index of all the arrays.
$[ = 1;

print "Food at \@foods[1]: $foods[1]\n";
print "Food at \@foods[2]: $foods[2]\n";


# Merging Arrays
# Because an array is just a comma-separated sequence of values, you can combine them together as shown below −


#!/usr/bin/perl

@numbers = (1,3,(4,5,6));

print "numbers = @numbers\n";

#!/usr/bin/perl

@odd = (1,3,5);
@even = (2, 4, 6);

@numbers = (@odd, @even);

print "numbers = @numbers\n";

# Selecting Elements from Lists
# The list notation is identical to that for arrays. You can extract an element from an array by appending square brackets to the list and giving one or more indices −


#!/usr/bin/perl

$var = (5,4,3,2,1)[4];

print "value of var = $var\n"

# Similarly, we can extract slices, although without the requirement for a leading @ character −


#!/usr/bin/perl

@list = (5,4,3,2,1)[1..3];

print "Value of list = @list\n";



# hashes
# A hash is a set of key/value pairs. Hash variables are preceded by a percent (%) sign. To refer to a single element of a hash, you will use the hash variable name preceded by a "$" sign and followed by the "key" associated with the value in curly brackets..


#!/usr/bin/perl

%data = ('John Paul', 45, 'Lisa', 30, 'Kumar', 40);

print "\$data{'John Paul'} = $data{'John Paul'}\n";
print "\$data{'Lisa'} = $data{'Lisa'}\n";
print "\$data{'Kumar'} = $data{'Kumar'}\n";

# Creating Hashes
# Hashes are created in one of the two following ways. In the first method, you assign a value to a named key on a one-by-one basis −

$data{'John Paul'} = 45;
$data{'Lisa'} = 30;
$data{'Kumar'} = 40;

# In the second case, you use a list, which is converted by taking individual pairs from the list: the first element of the pair is used as the key, and the second, as the value. For example −

%data = ('John Paul', 45, 'Lisa', 30, 'Kumar', 40);

# For clarity, you can use => as an alias for , to indicate the key/value pairs as follows −

%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);

# Here is one more variant of the above form, have a look at it, here all the keys have been preceded by hyphen (-) and no quotation is required around them −

%data = (-JohnPaul => 45, -Lisa => 30, -Kumar => 40);

# But it is important to note that there is a single word, i.e., without spaces keys have been used in this form of hash formation and if you build-up your hash this way then keys will be accessed using hyphen only as shown below.

$val = %data{-JohnPaul}
$val = %data{-Lisa}


# Accessing Hash Elements
# When accessing individual elements from a hash, you must prefix the variable with a dollar sign ($) and then append the element key within curly brackets after the name of the variable. For example −


#!/usr/bin/perl

%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);

print "$data{'John Paul'}\n";
print "$data{'Lisa'}\n";
print "$data{'Kumar'}\n";

# Extracting Slices
# You can extract slices of a hash just as you can extract slices from an array. You will need to use @ prefix for the variable to store the returned value because they will be a list of values −


#!/uer/bin/perl


%data = (-JohnPaul => 45, -Lisa => 30, -Kumar => 40);

@array = @data{-JohnPaul, -Lisa};

print "Array : @array\n";
This will produce the following result −

Array : 45 30


# Extracting Keys and Values
# You can get a list of all of the keys from a hash by using keys function, which has the following syntax −

keys %HASH


# This function returns an array of all the keys of the named hash. Following is the example −

#!/usr/bin/perl 

%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);

@names = keys %data;

print "$names[0]\n";
print "$names[1]\n";
print "$names[2]\n";

# Similarly, you can use values function to get a list of all the values. This function has the following syntax −

# values %HASH

# This function returns a normal array consisting of all the values of the named hash. Following is the example −

#!/usr/bin/perl 

%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);

@ages = values %data;

print "$ages[0]\n";
print "$ages[1]\n";
print "$ages[2]\n";

# Checking for Existence
# If you try to access a key/value pair from a hash that doesn't exist, you'll normally get the undefined value, and if you have warnings switched on, then you'll get a warning generated at run time. You can get around this by using the exists function, which returns true if the named key exists, irrespective of what its value might be −


#!/usr/bin/perl

%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);

if( exists($data{'Lisa'} ) ) {
   print "Lisa is $data{'Lisa'} years old\n";
} else {
   print "I don't know age of Lisa\n";
}


# Getting Hash Size
# You can get the size - that is, the number of elements from a hash by using the scalar context on either keys or values. Simply saying first you have to get an array of either the keys or values and then you can get the size of array as follows −

#!/usr/bin/perl

%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);

@keys = keys %data;
$size = @keys;
print "1 - Hash size:  is $size\n";

@values = values %data;
$size = @values;
print "2 - Hash size:  is $size\n";


# Add and Remove Elements in Hashes
# Adding a new key/value pair can be done with one line of code using simple assignment operator. But to remove an element from the hash you need to use delete function as shown below in the example −

#!/usr/bin/perl

%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);
@keys = keys %data;
$size = @keys;
print "1 - Hash size:  is $size\n";

# adding an element to the hash;
$data{'Ali'} = 55;
@keys = keys %data;
$size = @keys;
print "2 - Hash size:  is $size\n";

# delete the same element from the hash;
delete $data{'Ali'};
@keys = keys %data;
$size = @keys;



# CONDITIONALS

# if
#!/usr/local/bin/perl
 
$a = 10;
# check the boolean condition using if statement
if( $a < 20 ) {
   # if condition is true then print the following
   printf "a is less than 20\n";
}
print "value of a is : $a\n";

$a = "";
# check the boolean condition using if statement
if( $a ) {
   # if condition is true then print the following
   printf "a has a true value\n";
}
print "value of a is : $a\n";



#!/usr/local/bin/perl
 
$a = 100;
# check the boolean condition using if statement
if( $a < 20 ) {
   # if condition is true then print the following
   printf "a is less than 20\n";
} else { 
   # if condition is false then print the following
   printf "a is greater than 20\n";
}
print "value of a is : $a\n";

$a = "";
# check the boolean condition using if statement
if( $a ) {
   # if condition is true then print the following
   printf "a has a true value\n";
} else {
   # if condition is false then print the following
   printf "a has a false value\n";
}
print "value of a is : $a\n";



#!/usr/local/bin/perl
 
$a = 100;
# check the boolean condition using if statement
if( $a  ==  20 ) {
   # if condition is true then print the following
   printf "a has a value which is 20\n";
} elsif( $a ==  30 ) {
   # if condition is true then print the following
   printf "a has a value which is 30\n";
} else {
   # if none of the above conditions is true
   printf "a has a value which is $a\n";
}



# UNLESS
#!/usr/local/bin/perl
 
$a = 20;
# check the boolean condition using unless statement
unless( $a < 20 ) {
   # if condition is false then print the following
   printf "a is not less than 20\n";
}
print "value of a is : $a\n";

$a = "";
# check the boolean condition using unless statement
unless ( $a ) {
   # if condition is false then print the following
   printf "a has a false value\n";
}
print "value of a is : $a\n";


#!/usr/local/bin/perl
 
$a = 100;
# check the boolean condition using unless statement
unless( $a == 20 ) {
   # if condition is false then print the following
   printf "given condition is false\n";
} else { 
   # if condition is true then print the following
   printf "given condition is true\n";
}
print "value of a is : $a\n";

$a = "";
# check the boolean condition using unless statement
unless( $a ) {
   # if condition is false then print the following
   printf "a has a false value\n";
} else {
   # if condition is true then print the following
   printf "a has a true value\n";
}
print "value of a is : $a\n";



#!/usr/local/bin/perl
 
$a = 20;
# check the boolean condition using if statement
unless( $a  ==  30 ) {
   # if condition is false then print the following
   printf "a has a value which is not 20\n";
} elsif( $a ==  30 ) {
   # if condition is true then print the following
   printf "a has a value which is 30\n";
} else {
   # if none of the above conditions is met
   printf "a has a value which is $a\n";
}




#SWITCH

#!/usr/local/bin/perl

use Switch;

$var = 10;
@array = (10, 20, 30);
%hash = ('key1' => 10, 'key2' => 20);

switch($var) {
   case 10           { print "number 100\n" }
   case "a"          { print "string a" }
   case [1..10,42]   { print "number in list" }
   case (\@array)    { print "number in list" }
   case (\%hash)     { print "entry in hash" }
   else              { print "previous case not true" }
}

#!/usr/local/bin/perl

use Switch;

$var = 10;
@array = (10, 20, 30);
%hash = ('key1' => 10, 'key2' => 20);

switch($var) {
   case 10           { print "number 100\n"; next; }
   case "a"          { print "string a" }
   case [1..10,42]   { print "number in list" }
   case (\@array)    { print "number in list" }
   case (\%hash)     { print "entry in hash" }
   else              { print "previous case not true" }
}


print "3 - Hash size:  is $size\n";
	
# Interpolative

# This context only happens inside quotes, or things that work like quotes.
# Welcome\ to\ tutorialspoint\'s\ family


# he ? : Operator
# Let's check the conditional operator ? :which can be used to replace if...else statements. It has the following general form −

# Exp1 ? Exp2 : Exp3;
# Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon.

# The value of a ? expression is determined like this: Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes the value of the entire ? expression. If Exp1 is false, then Exp3 is evaluated and its value becomes the value of the expression. Below is a simple example making use of this operator −

#!/usr/local/bin/perl
 
$name = "Ali";
$age = 10;



# LOOPS

# WHILE LOOP
#!/usr/local/bin/perl
 
$a = 10;

# while loop execution
while( $a < 20 ) {
   printf "Value of a: $a\n";
   $a = $a + 1;
}

#!/usr/local/bin/perl
 
$a = 5;


# UNTIL LOOP
# until loop execution
until( $a > 10 ) {
   printf "Value of a: $a\n";
   $a = $a + 1;
}


#!/usr/local/bin/perl

# FOR LOOP 
# for loop execution
for( $a = 10; $a < 20; $a = $a + 1 ) {
   print "value of a: $a\n";
}




# FOREACH LOOP
#!/usr/local/bin/perl
 
@list = (2, 20, 30, 40, 50);

# foreach loop execution
foreach $a (@list) {
   print "value of a: $a\n";
}



$status = ($age > 60 )? "A senior citizen" : "Not a senior citizen";

print "$name is  - $status\n";



# DOWHILE LOOP
#!/usr/local/bin/perl
 
$a = 10;

# do...while loop execution
do{
   printf "Value of a: $a\n";
   $a = $a + 1;
}while( $a < 20 );



# NESTED LOOP
#/usr/local/bin/perl
   
$a = 0;
$b = 0;

# outer while loop
while($a < 3) {
   $b = 0;
   # inner while loop
   while( $b < 3 ) {
      print "value of a = $a, b = $b\n";
      $b = $b + 1;
   }
   $a = $a + 1;
   print "Value of a = $a\n\n";
}






# LOOP CONTROL


# NEXT
#!/usr/local/bin/perl

$a = 10;
while( $a < 20 ) {
   if( $a == 15) {
      # skip the iteration.
      $a = $a + 1;
      next;
   }
   print "value of a: $a\n";
   $a = $a + 1;
}


# NEXT WITH KEYWORD
#!/usr/local/bin/perl

$a = 0;
OUTER: while( $a < 4 ) {
   $b = 0;
   print "value of a: $a\n";
   INNER:while ( $b < 4) {
      if( $a == 2) {
         $a = $a + 1;
         # jump to outer loop
         next OUTER;
      }
      $b = $b + 1;
      print "Value of b : $b\n";
   }
   print "\n";
   $a = $a + 1;
   
}

# LAST
#!/usr/local/bin/perl

$a = 10;
while( $a < 20 ) {
   if( $a == 15) {
      # terminate the loop.
      $a = $a + 1;
      last;
   }
   print "value of a: $a\n";
   $a = $a + 1;
}


# LAST WITH KEYWORD
#!/usr/local/bin/perl

$a = 0;
OUTER: while( $a < 4 ) {
   $b = 0;
   print "value of a: $a\n";
   INNER:while ( $b < 4) {
      if( $a == 2) {
         # terminate outer loop
         last OUTER;
      }
      $b = $b + 1;
      print "Value of b : $b\n";
   }
   print "\n";
   $a = $a + 1;
}


# CONTINUE
#/usr/local/bin/perl
   
$a = 0;
while($a < 3) {
   print "Value of a = $a\n";
} continue {
   $a = $a + 1;
}


# CONTINUE WITH FOREACH
#/usr/local/bin/perl
   
@list = (1, 2, 3, 4, 5);
foreach $a (@list) {
   print "Value of a = $a\n";
} continue {
   last if $a == 4;
}


# REDO
#/usr/local/bin/perl
   
$a = 0;
while($a < 10) {
   if( $a == 5 ) {
      $a = $a + 1;
      redo;
   }
   print "Value of a = $a\n";
} continue {
   $a = $a + 1;
}



# GO TO
#/usr/local/bin/perl
   
$a = 10;

LOOP:do {
   if( $a == 15) {
      # skip the iteration.
      $a = $a + 1;
      # use goto LABEL form
      goto LOOP;
   }
   print "Value of a = $a\n";
   $a = $a + 1;
} while( $a < 20 );


# GOTO WITH KEYWORD
#/usr/local/bin/perl
   
$a = 10;
$str1 = "LO";
$str2 = "OP";

LOOP:do {
   if( $a == 15) {
      # skip the iteration.
      $a = $a + 1;
      # use goto EXPR form
      goto $str1.$str2;
   }
   print "Value of a = $a\n";
   $a = $a + 1;
} while( $a < 20 );




# INFINITE LOOP
#!/usr/local/bin/perl
 
for( ; ; ) {
   printf "This loop will run forever.\n";
}


# SUBROUTINES
# Define and Call a Subroutine
# The general form of a subroutine definition in Perl programming language is as follows −

# sub subroutine_name {
   # body of the subroutine
# }
# The typical way of calling that Perl subroutine is as follows −

# subroutine_name( list of arguments );
# In versions of Perl before 5.0, the syntax for calling subroutines was slightly different as shown below. This still works in the newest versions of Perl, but it is not recommended since it bypasses the subroutine prototypes.

# &subroutine_name( list of arguments );
# Let's have a look into the following example, which defines a simple function and then call it. Because Perl compiles your program before executing it, it doesn't matter where you declare your subroutine.


#!/usr/bin/perl

# Function definition
sub Hello {
   print "Hello, World!\n";
}

# Function call
Hello();


Passing Arguments to a Subroutine
You can pass various arguments to a subroutine like you do in any other programming language and they can be acessed inside the function using the special array @_. Thus the first argument to the function is in $_[0], the second is in $_[1], and so on.

You can pass arrays and hashes as arguments like any scalar but passing more than one array or hash normally causes them to lose their separate identities. So we will use references ( explained in the next chapter ) to pass any array or hash.



#!/usr/bin/perl

# Function definition
sub Average {
   # get total number of arguments passed.
   $n = scalar(@_);
   $sum = 0;

   foreach $item (@_) {
      $sum += $item;
   }
   $average = $sum / $n;

   print "Average for the given numbers : $average\n";
}

# Function call
Average(10, 20, 30);

# Passing Lists to Subroutines
# Because the @_ variable is an array, it can be used to supply lists to a subroutine. However, because of the way in which Perl accepts and parses lists and arrays, it can be difficult to extract the individual elements from @_. If you have to pass a list along with other scalar arguments, then make list as the last argument as shown below −


#!/usr/bin/perl

# Function definition
sub PrintList {
   my @list = @_;
   print "Given list is @list\n";
}
$a = 10;
@b = (1, 2, 3, 4);

# Function call with list parameter
PrintList($a, @b);


# Passing Hashes to Subroutines
# When you supply a hash to a subroutine or operator that accepts a list, then hash is automatically translated into a list of key/value pairs. For example −

#!/usr/bin/perl

# Function definition
sub PrintHash {
   my (%hash) = @_;

   foreach my $key ( keys %hash ) {
      my $value = $hash{$key};
      print "$key : $value\n";
   }
}
%hash = ('name' => 'Tom', 'age' => 19);

# Function call with hash parameter
PrintHash(%hash);

# Returning Value from a Subroutine
# You can return a value from subroutine like you do in any other programming language. If you are not returning a value from a subroutine then whatever calculation is last performed in a subroutine is automatically also the return value.

# You can return arrays and hashes from the subroutine like any scalar but returning more than one array or hash normally causes them to lose their separate identities. So we will use references ( explained in the next chapter ) to return any array or hash from a function.

#!/usr/bin/perl

# Function definition
sub Average {
   # get total number of arguments passed.
   $n = scalar(@_);
   $sum = 0;

   foreach $item (@_) {
      $sum += $item;
   }
   $average = $sum / $n;

   return $average;
}

# Function call
$num = Average(10, 20, 30);
print "Average for the given numbers : $num\n";

# Private Variables in a Subroutine
# By default, all variables in Perl are global variables, which means they can be accessed from anywhere in the program. But you can create private variables called lexical variables at any time with the my operator.

# The my operator confines a variable to a particular region of code in which it can be used and accessed. Outside that region, this variable cannot be used or accessed. This region is called its scope. A lexical scope is usually a block of code with a set of braces around it, such as those defining the body of the subroutine or those marking the code blocks of if, while, for, foreach, and eval statements.



sub somefunc {
   my $variable; # $variable is invisible outside somefunc()
   my ($another, @an_array, %a_hash); # declaring many variables at once
}

#!/usr/bin/perl

# Global variable
$string = "Hello, World!";

# Function definition
sub PrintHello {
   # Private variable for PrintHello function
   my $string;
   $string = "Hello, Perl!";
   print "Inside the function $string\n";
}
# Function call
PrintHello();
print "Outside the function $string\n";


# Temporary Values via local()
# The local is mostly used when the current value of a variable must be visible to called subroutines. A local just gives temporary values to global (meaning package) variables. This is known as dynamic scoping. Lexical scoping is done with my, which works more like C's auto declarations.

# If more than one variable or expression is given to local, they must be placed in parentheses. This operator works by saving the current values of those variables in its argument list on a hidden stack and restoring them upon exiting the block, subroutine, or eval.


#!/usr/bin/perl

# Global variable
$string = "Hello, World!";

sub PrintHello {
   # Private variable for PrintHello function
   local $string;
   $string = "Hello, Perl!";
   PrintMe();
   print "Inside the function PrintHello $string\n";
}
sub PrintMe {
   print "Inside the function PrintMe $string\n";
}

# Function call
PrintHello();
print "Outside the function $string\n";

State Variables via state()
There are another type of lexical variables, which are similar to private variables but they maintain their state and they do not get reinitialized upon multiple calls of the subroutines. These variables are defined using the state operator and available starting from Perl 5.9.4.


#!/usr/bin/perl

use feature 'state';

sub PrintCount {
   state $count = 0; # initial value

   print "Value of counter is $count\n";
   $count++;
}

for (1..5) {
   PrintCount();
}

#!/usr/bin/perl

{
   my $count = 0; # initial value

   sub PrintCount {
      print "Value of counter is $count\n";
      $count++;
   }
}

for (1..5) {
   PrintCount();
}


# Subroutine Call Context
# The context of a subroutine or statement is defined as the type of return value that is expected. This allows you to use a single function that returns different values based on what the user is expecting to receive. For example, the following localtime() returns a string when it is called in scalar context, but it returns a list when it is called in list context.

my $datestring = localtime( time );

# In this example, the value of $timestr is now a string made up of the current date and time, for example, Thu Nov 30 15:21:33 2000. Conversely −

# ($sec,$min,$hour,$mday,$mon, $year,$wday,$yday,$isdst) = localtime(time);









# Create References
# It is easy to create a reference for any variable, subroutine or value by prefixing it with a backslash as follows −

$scalarref = \$foo;
$arrayref  = \@ARGV;
$hashref   = \%ENV;
$coderef   = \&handler;
$globref   = \*foo;


# You cannot create a reference on an I/O handle (filehandle or dirhandle) using the backslash operator but a reference to an anonymous array can be created using the square brackets as follows −

 $arrayref = [1, 2, ['a', 'b', 'c']];
 
 
# Similar way you can create a reference to an anonymous hash using the curly brackets as follows −

$hashref = {
   'Adam'  => 'Eve',
   'Clyde' => 'Bonnie',
};


# A reference to an anonymous subroutine can be created by using sub without a subname as follows −

$coderef = sub { print "Boink!\n" };



# Dereferencing
# Dereferencing returns the value from a reference point to the location. To dereference a reference simply use $, @ or % as prefix of the reference variable depending on whether the reference is pointing to a scalar, array, or hash. Following is the example to explain the concept −

#!/usr/bin/perl

$var = 10;

# Now $r has reference to $var scalar.
$r = \$var;

# Print value available at the location stored in $r.
print "Value of $var is : ", $$r, "\n";

@var = (1, 2, 3);
# Now $r has reference to @var array.
$r = \@var;
# Print values available at the location stored in $r.
print "Value of @var is : ",  @$r, "\n";

%var = ('key1' => 10, 'key2' => 20);
# Now $r has reference to %var hash.
$r = \%var;
# Print values available at the location stored in $r.
print "Value of %var is : ", %$r, "\n";

# If you are not sure about a variable type, then its easy to know its type using ref, which returns one of the following strings if its argument is a reference. Otherwise, it returns false −

# SCALAR
# ARRAY
# HASH
# CODE
# GLOB
# REF
# Let's try the following example −

Live Demo
#!/usr/bin/perl

$var = 10;
$r = \$var;
print "Reference type in r : ", ref($r), "\n";

@var = (1, 2, 3);
$r = \@var;
print "Reference type in r : ", ref($r), "\n";

%var = ('key1' => 10, 'key2' => 20);
$r = \%var;
print "Reference type in r : ", ref($r), "\n";

# Circular References
# A circular reference occurs when two references contain a reference to each other. You have to be careful while creating references otherwise a circular reference can lead to memory leaks. Following is an example −


#!/usr/bin/perl

 my $foo = 100;
 $foo = \$foo;
 
 print "Value of foo is : ", $$foo, "\n";

 
# References to Functions
# This might happen if you need to create a signal handler so you can produce a reference to a function by preceding that function name with \& and to dereference that reference you simply need to prefix reference variable using ampersand &. Following is an example −


#!/usr/bin/perl

# Function definition
sub PrintHash {
   my (%hash) = @_;
   
   foreach $item (%hash) {
      print "Item : $item\n";
   }
}
%hash = ('name' => 'Tom', 'age' => 19);

# Create a reference to above function.
$cref = \&PrintHash;

# Function call using reference.
&$cref(%hash);


# FORMATS

#!/usr/bin/perl

format EMPLOYEE =
===================================
@<<<<<<<<<<<<<<<<<<<<<< @<< 
$name $age
@#####.##
$salary
===================================
.

select(STDOUT);
$~ = EMPLOYEE;

@n = ("Ali", "Raza", "Jaffer");
@a  = (20,30, 40);
@s = (2000.00, 2500.00, 4000.000);

$i = 0;
foreach (@n) {
   $name = $_;
   $age = $a[$i];
   $salary = $s[$i++];
   write;
}

#!/usr/bin/perl

format EMPLOYEE =
===================================
@<<<<<<<<<<<<<<<<<<<<<< @<< 
$name $age
@#####.##
$salary
===================================
.

format EMPLOYEE_TOP =
===================================
Name                    Age
===================================
.

select(STDOUT);
$~ = EMPLOYEE;
$^ = EMPLOYEE_TOP;

@n = ("Ali", "Raza", "Jaffer");
@a  = (20,30, 40);
@s = (2000.00, 2500.00, 4000.000);

$i = 0;
foreach (@n) {
   $name = $_;
   $age = $a[$i];
   $salary = $s[$i++];
   write;
}




# Opening and Closing Files
# There are following two functions with multiple forms, which can be used to open any new or existing file in Perl.

open FILEHANDLE, EXPR
open FILEHANDLE

sysopen FILEHANDLE, FILENAME, MODE, PERMS
sysopen FILEHANDLE, FILENAME, MODE

# Here FILEHANDLE is the file handle returned by the open function and EXPR is the expression having file name and mode of opening the file.

# Open Function
# Following is the syntax to open file.txt in read-only mode. Here less than < sign indicates that file has to be opend in read-only mode.

open(DATA, "<file.txt");

# Here DATA is the file handle, which will be used to read the file. Here is the example, which will open a file and will print its content over the screen.

#!/usr/bin/perl

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

while(<DATA>) {
   print "$_";
}


# Following is the syntax to open file.txt in writing mode. Here less than > sign indicates that file has to be opend in the writing mode.

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

# This example actually truncates (empties) the file before opening it for writing, which may not be the desired effect. If you want to open a file for reading and writing, you can put a plus sign before the > or < characters.

# For example, to open a file for updating without truncating it −

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

# To truncate the file first −

open DATA, "+>file.txt" or die "Couldn't open file file.txt, $!";

# You can open a file in the append mode. In this mode, writing point will be set to the end of the file.

open(DATA,">>file.txt") || die "Couldn't open file file.txt, $!";

# A double >> opens the file for appending, placing the file pointer at the end, so that you can immediately start appending information. However, you can't read from it unless you also place a plus sign in front of it −

open(DATA,"+>>file.txt") || die "Couldn't open file file.txt, $!";


# Sysopen Function
# The sysopen function is similar to the main open function, except that it uses the system open() function, using the parameters supplied to it as the parameters for the system function −

# For example, to open a file for updating, emulating the +<filename format from open −

sysopen(DATA, "file.txt", O_RDWR);

# Or to truncate the file before updating −

sysopen(DATA, "file.txt", O_RDWR|O_TRUNC );

# You can use O_CREAT to create a new file and O_WRONLY- to open file in write only mode and O_RDONLY - to open file in read only mode.

# The PERMS argument specifies the file permissions for the file specified, if it has to be created. By default it takes 0x666.

# Following is the table, which gives the possible values of MODE.



# Close Function
# To close a filehandle, and therefore disassociate the filehandle from the corresponding file, you use the close function. This flushes the filehandle's buffers and closes the system's file descriptor.

close FILEHANDLE
close

# If no FILEHANDLE is specified, then it closes the currently selected filehandle. It returns true only if it could successfully flush the buffers and close the file.

close(DATA) || die "Couldn't close file properly";

# Reading and Writing Files
# Once you have an open filehandle, you need to be able to read and write information. There are a number of different ways of reading and writing data into the file.

# The <FILEHANDL> Operator
# The main method of reading the information from an open filehandle is the <FILEHANDLE> operator. In a scalar context, it returns a single line from the filehandle. For example −

#!/usr/bin/perl

print "What is your name?\n";
$name = <STDIN>;
print "Hello $name\n";

# When you use the <FILEHANDLE> operator in a list context, it returns a list of lines from the specified filehandle. For example, to import all the lines from a file into an array −

#!/usr/bin/perl

open(DATA,"<import.txt") or die "Can't open data";
@lines = <DATA>;
close(DATA);
getc Function

# The getc function returns a single character from the specified FILEHANDLE, or STDIN if none is specified −

getc FILEHANDLE
getc

# If there was an error, or the filehandle is at end of file, then undef is returned instead.

# read Function
# The read function reads a block of information from the buffered filehandle: This function is used to read binary data from the file.

read FILEHANDLE, SCALAR, LENGTH, OFFSET
read FILEHANDLE, SCALAR, LENGTH

# The length of the data read is defined by LENGTH, and the data is placed at the start of SCALAR if no OFFSET is specified. Otherwise data is placed after OFFSET bytes in SCALAR. The function returns the number of bytes read on success, zero at end of file, or undef if there was an error.

print Function

# For all the different methods used for reading information from filehandles, the main function for writing information back is the print function.

print FILEHANDLE LIST
print LIST
print

# The print function prints the evaluated value of LIST to FILEHANDLE, or to the current output filehandle (STDOUT by default). For example −

print "Hello World!\n";



# Copying Files
# Here is the example, which opens an existing file file1.txt and read it line by line and generate another copy file file2.txt.

#!/usr/bin/perl

# Open file to read
open(DATA1, "<file1.txt");

# Open new file to write
open(DATA2, ">file2.txt");

# Copy data from one file to another.
while(<DATA1>) {
   print DATA2 $_;
}
close( DATA1 );
close( DATA2 );


# Renaming a file
# Here is an example, which shows how we can rename a file file1.txt to file2.txt. Assuming file is available in /usr/test directory.

#!/usr/bin/perl

rename ("/usr/test/file1.txt", "/usr/test/file2.txt" );

# Deleting an Existing File
# Here is an example, which shows how to delete a file file1.txt using the unlink function.

#!/usr/bin/perl

unlink ("/usr/test/file1.txt");

# Positioning inside a File
# You can use to tell function to know the current position of a file and seek function to point a particular position inside the file.

tell Function

# The first requirement is to find your position within a file, which you do using the tell function −

tell FILEHANDLE
tell

# This returns the position of the file pointer, in bytes, within FILEHANDLE if specified, or the current default selected filehandle if none is specified.

seek Function

# The seek function positions the file pointer to the specified number of bytes within a file −

seek FILEHANDLE, POSITION, WHENCE

# The function uses the fseek system function, and you have the same ability to position relative to three different points: the start, the end, and the current position. You do this by specifying a value for WHENCE.

# Zero sets the positioning relative to the start of the file. For example, the line sets the file pointer to the 256th byte in the file.

seek DATA, 256, 0;


# File Information
# You can test certain features very quickly within Perl using a series of test operators known collectively as -X tests. For example, to perform a quick test of the various permissions on a file, you might use a script like this −

#/usr/bin/perl

my $file = "/usr/test/file1.txt";
my (@description, $size);
if (-e $file) {
   push @description, 'binary' if (-B _);
   push @description, 'a socket' if (-S _);
   push @description, 'a text file' if (-T _);
   push @description, 'a block special file' if (-b _);
   push @description, 'a character special file' if (-c _);
   push @description, 'a directory' if (-d _);
   push @description, 'executable' if (-x _);
   push @description, (($size = -s _)) ? "$size bytes" : 'empty';
   print "$file is ", join(', ',@description),"\n";
}



opendir DIRHANDLE, EXPR  # To open a directory
readdir DIRHANDLE        # To read a directory
rewinddir DIRHANDLE      # Positioning pointer to the begining
telldir DIRHANDLE        # Returns current position of the dir
seekdir DIRHANDLE, POS   # Pointing pointer to POS inside dir
closedir DIRHANDLE       # Closing a directory.


# Display all the Files
# There are various ways to list down all the files available in a particular directory. First let's use the simple way to get and list down all the files using the glob operator −

#!/usr/bin/perl

# Display all the files in /tmp directory.
$dir = "/tmp/*";
my @files = glob( $dir );

foreach (@files ) {
   print $_ . "\n";
}

# Display all the C source files in /tmp directory.
$dir = "/tmp/*.c";
@files = glob( $dir );

foreach (@files ) {
   print $_ . "\n";
}

# Display all the hidden files.
$dir = "/tmp/.*";
@files = glob( $dir );
foreach (@files ) {
   print $_ . "\n";
}

# Display all the files from /tmp and /home directories.
$dir = "/tmp/* /home/*";
@files = glob( $dir );

foreach (@files ) {
   print $_ . "\n";
}


# Here is another example, which opens a directory and list out all the files available inside this directory.

#!/usr/bin/perl

opendir (DIR, '.') or die "Couldn't open directory, $!";
while ($file = readdir DIR) {
   print "$file\n";
}
closedir DIR;
One more example to print the list of C source files you might use is −

#!/usr/bin/perl

opendir(DIR, '.') or die "Couldn't open directory, $!";
foreach (sort grep(/^.*\.c$/,readdir(DIR))) {
   print "$_\n";
}
closedir DIR;



# Create new Directory
# You can use mkdir function to create a new directory. You will need to have the required permission to create a directory.

#!/usr/bin/perl

$dir = "/tmp/perl";

# This creates perl directory in /tmp directory.
mkdir( $dir ) or die "Couldn't create $dir directory, $!";
print "Directory created successfully\n";


# Remove a directory
# You can use rmdir function to remove a directory. You will need to have the required permission to remove a directory. Additionally this directory should be empty before you try to remove it.

#!/usr/bin/perl

$dir = "/tmp/perl";

# This removes perl directory from /tmp directory.
rmdir( $dir ) or die "Couldn't remove $dir directory, $!";
print "Directory removed successfully\n";


# Change a Directory
# You can use chdir function to change a directory and go to a new location. You will need to have the required permission to change a directory and go inside the new directory.

#!/usr/bin/perl

$dir = "/home";

# This changes perl directory  and moves you inside /home directory.
chdir( $dir ) or die "Couldn't go inside $dir directory, $!";
print "Your new location is $dir\n";

Global Scalar Special Variables
Here is the list of all the scalar special variables. We have listed corresponding english like names along with the symbolic names.

$_	The default input and pattern-searching space.
$ARG
$.	The current input line number of the last filehandle that was read. An explicit close on the filehandle resets the line number.
$NR
$/	The input record separator; newline by default. If set to the null string, it treats blank lines as delimiters.
$RS
$,	The output field separator for the print operator.
$OFS
$\	The output record separator for the print operator.
$ORS
$"	Like "$," except that it applies to list values interpolated into a double-quoted string (or similar interpreted string). Default is a space.
$LIST_SEPARATOR
$;	The subscript separator for multidimensional array emulation. Default is "\034".
$SUBSCRIPT_SEPARATOR
$^L	What a format outputs to perform a formfeed. Default is "\f".
$FORMAT_FORMFEED
$:	The current set of characters after which a string may be broken to fill continuation fields (starting with ^) in a format. Default is "\n"".
$FORMAT_LINE_BREAK_CHARACTERS
$^A	The current value of the write accumulator for format lines.
$ACCUMULATOR
$#	Contains the output format for printed numbers (deprecated).
$OFMT
$?	The status returned by the last pipe close, backtick (``) command, or system operator.
$CHILD_ERROR
$!	If used in a numeric context, yields the current value of the errno variable, identifying the last system call error. If used in a string context, yields the corresponding system error string.
$OS_ERROR or $ERRNO
$@	The Perl syntax error message from the last eval command.
$EVAL_ERROR
$$	The pid of the Perl process running this script.
$PROCESS_ID or $PID
$<	The real user ID (uid) of this process.
$REAL_USER_ID or $UID
$>	The effective user ID of this process.
$EFFECTIVE_USER_ID or $EUID
$(	The real group ID (gid) of this process.
$REAL_GROUP_ID or $GID
$)	The effective gid of this process.
$EFFECTIVE_GROUP_ID or $EGID
$0	Contains the name of the file containing the Perl script being executed.
$PROGRAM_NAME
$[	The index of the first element in an array and of the first character in a substring. Default is 0.
$]	Returns the version plus patchlevel divided by 1000.
$PERL_VERSION
$^D	The current value of the debugging flags.
$DEBUGGING
$^E	Extended error message on some platforms.
$EXTENDED_OS_ERROR
$^F	The maximum system file descriptor, ordinarily 2.
$SYSTEM_FD_MAX
$^H	Contains internal compiler hints enabled by certain pragmatic modules.
$^I	The current value of the inplace-edit extension. Use undef to disable inplace editing.
$INPLACE_EDIT
$^M	The contents of $M can be used as an emergency memory pool in case Perl dies with an out-of-memory error. Use of $M requires a special compilation of Perl. See the INSTALL document for more information.
$^O	Contains the name of the operating system that the current Perl binary was compiled for.
$OSNAME
$^P	The internal flag that the debugger clears so that it doesn't debug itself.
$PERLDB
$^T	The time at which the script began running, in seconds since the epoch.
$BASETIME
$^W	The current value of the warning switch, either true or false.
$WARNING
$^X	The name that the Perl binary itself was executed as.
$EXECUTABLE_NAME
$ARGV	Contains the name of the current file when reading from <ARGV>.
Global Array Special Variables
@ARGV	The array containing the command-line arguments intended for the script.
@INC	The array containing the list of places to look for Perl scripts to be evaluated by the do, require, or use constructs.
@F	The array into which the input lines are split when the -a command-line switch is given.
Global Hash Special Variables
%INC	The hash containing entries for the filename of each file that has been included via do or require.
%ENV	The hash containing your current environment.
%SIG	The hash used to set signal handlers for various signals.
Global Special Filehandles
ARGV	The special filehandle that iterates over command line filenames in @ARGV. Usually written as the null filehandle in <>.
STDERR	The special filehandle for standard error in any package.
STDIN	The special filehandle for standard input in any package.
STDOUT	The special filehandle for standard output in any package.
DATA	The special filehandle that refers to anything following the __END__ token in the file containing the script. Or, the special filehandle for anything following the __DATA__ token in a required file, as long as you're reading data in the same package __DATA__ was found in.
_ (underscore)	The special filehandle used to cache the information from the last stat, lstat, or file test operator.
Global Special Constants
__END__	Indicates the logical end of your program. Any following text is ignored, but may be read via the DATA filehandle.
__FILE__	Represents the filename at the point in your program where it's used. Not interpolated into strings.
__LINE__	Represents the current line number. Not interpolated into strings.
__PACKAGE__	Represents the current package name at compile time, or undefined if there is no current package. Not interpolated into strings.
Regular Expression Special Variables
$digit	Contains the text matched by the corresponding set of parentheses in the last pattern matched. For example, $1 matches whatever was contained in the first set of parentheses in the previous regular expression.
$&	The string matched by the last successful pattern match.
$MATCH
$`	The string preceding whatever was matched by the last successful pattern match.
$PREMATCH
$'	The string following whatever was matched by the last successful pattern match.
$POSTMATCH
$+	The last bracket matched by the last search pattern. This is useful if you don't know which of a set of alternative patterns was matched. For example : /Version: (.*)|Revision: (.*)/ && ($rev = $+);
$LAST_PAREN_MATCH
Filehandle Special Variables
$|	If set to nonzero, forces an fflush(3) after every write or print on the currently selected output channel.
$OUTPUT_AUTOFLUSH
$%	The current page number of the currently selected output channel.
$FORMAT_PAGE_NUMBER
$=	The current page length (printable lines) of the currently selected output channel. Default is 60.
$FORMAT_LINES_PER_PAGE
$-	The number of lines left on the page of the currently selected output channel.
$FORMAT_LINES_LEFT
$~	The name of the current report format for the currently selected output channel. Default is the name of the filehandle.
$FORMAT_NAME
$^	The name of the current top-of-page format for the currently selected output channel. Default is the name of the filehandle with _TOP appended.





regex





The Match Operator
The match operator, m//, is used to match a string or statement to a regular expression. For example, to match the character sequence "foo" against the scalar $bar, you might use a statement like this −

Live Demo
#!/usr/bin/perl

$bar = "This is foo and again foo";
if ($bar =~ /foo/) {
   print "First time is matching\n";
} else {
   print "First time is not matching\n";
}

$bar = "foo";
if ($bar =~ /foo/) {
   print "Second time is matching\n";
} else {
   print "Second time is not matching\n";
}
When above program is executed, it produces the following result −

First time is matching
Second time is matching
The m// actually works in the same fashion as the q// operator series.you can use any combination of naturally matching characters to act as delimiters for the expression. For example, m{}, m(), and m>< are all valid. So above example can be re-written as follows −

#!/usr/bin/perl

$bar = "This is foo and again foo";
if ($bar =~ m[foo]) {
   print "First time is matching\n";
} else {
   print "First time is not matching\n";
}

$bar = "foo";
if ($bar =~ m{foo}) {
   print "Second time is matching\n";
} else {
   print "Second time is not matching\n";
}
You can omit m from m// if the delimiters are forward slashes, but for all other delimiters you must use the m prefix.

Note that the entire match expression, that is the expression on the left of =~ or !~ and the match operator, returns true (in a scalar context) if the expression matches. Therefore the statement −

$true = ($foo =~ m/foo/);
will set $true to 1 if $foo matches the regex, or 0 if the match fails. In a list context, the match returns the contents of any grouped expressions. For example, when extracting the hours, minutes, and seconds from a time string, we can use −

my ($hours, $minutes, $seconds) = ($time =~ m/(\d+):(\d+):(\d+)/);


Matching Only Once
There is also a simpler version of the match operator - the ?PATTERN? operator. This is basically identical to the m// operator except that it only matches once within the string you are searching between each call to reset.

For example, you can use this to get the first and last elements within a list −

Live Demo
#!/usr/bin/perl

@list = qw/food foosball subeo footnote terfoot canic footbrdige/;

foreach (@list) {
   $first = $1 if /(foo.*?)/;
   $last = $1 if /(foo.*)/;
}
print "First: $first, Last: $last\n";
When above program is executed, it produces the following result −


The Match Operator
The match operator, m//, is used to match a string or statement to a regular expression. For example, to match the character sequence "foo" against the scalar $bar, you might use a statement like this −

Live Demo
#!/usr/bin/perl

$bar = "This is foo and again foo";
if ($bar =~ /foo/) {
   print "First time is matching\n";
} else {
   print "First time is not matching\n";
}

$bar = "foo";
if ($bar =~ /foo/) {
   print "Second time is matching\n";
} else {
   print "Second time is not matching\n";
}
When above program is executed, it produces the following result −

First time is matching
Second time is matching
The m// actually works in the same fashion as the q// operator series.you can use any combination of naturally matching characters to act as delimiters for the expression. For example, m{}, m(), and m>< are all valid. So above example can be re-written as follows −

#!/usr/bin/perl

$bar = "This is foo and again foo";
if ($bar =~ m[foo]) {
   print "First time is matching\n";
} else {
   print "First time is not matching\n";
}

$bar = "foo";
if ($bar =~ m{foo}) {
   print "Second time is matching\n";
} else {
   print "Second time is not matching\n";
}
You can omit m from m// if the delimiters are forward slashes, but for all other delimiters you must use the m prefix.

Note that the entire match expression, that is the expression on the left of =~ or !~ and the match operator, returns true (in a scalar context) if the expression matches. Therefore the statement −

$true = ($foo =~ m/foo/);
will set $true to 1 if $foo matches the regex, or 0 if the match fails. In a list context, the match returns the contents of any grouped expressions. For example, when extracting the hours, minutes, and seconds from a time string, we can use −

my ($hours, $minutes, $seconds) = ($time =~ m/(\d+):(\d+):(\d+)/);
Match Operator Modifiers
The match operator supports its own set of modifiers. The /g modifier allows for global matching. The /i modifier will make the match case insensitive. Here is the complete list of modifiers

Sr.No.	Modifier & Description
1	
i

Makes the match case insensitive.

2	
m

Specifies that if the string has newline or carriage return characters, the ^ and $ operators will now match against a newline boundary, instead of a string boundary.

3	
o

Evaluates the expression only once.

4	
s

Allows use of . to match a newline character.

5	
x

Allows you to use white space in the expression for clarity.

6	
g

Globally finds all matches.

7	
cg

Allows the search to continue even after a global match fails.

Matching Only Once
There is also a simpler version of the match operator - the ?PATTERN? operator. This is basically identical to the m// operator except that it only matches once within the string you are searching between each call to reset.

For example, you can use this to get the first and last elements within a list −

Live Demo
#!/usr/bin/perl

@list = qw/food foosball subeo footnote terfoot canic footbrdige/;

foreach (@list) {
   $first = $1 if /(foo.*?)/;
   $last = $1 if /(foo.*)/;
}
print "First: $first, Last: $last\n";
When above program is executed, it produces the following result −

First: foo, Last: footbrdige
Regular Expression Variables
Regular expression variables include $, which contains whatever the last grouping match matched; $&, which contains the entire matched string; $`, which contains everything before the matched string; and $', which contains everything after the matched string. Following code demonstrates the result −

Live Demo
#!/usr/bin/perl

$string = "The food is in the salad bar";
$string =~ m/foo/;
print "Before: $`\n";
print "Matched: $&\n";
print "After: $'\n";
When above program is executed, it produces the following result −

Before: The
Matched: foo
After: d is in the salad bar
The Substitution Operator
The substitution operator, s///, is really just an extension of the match operator that allows you to replace the text matched with some new text. The basic form of the operator is −

s/PATTERN/REPLACEMENT/;
The PATTERN is the regular expression for the text that we are looking for. The REPLACEMENT is a specification for the text or regular expression that we want to use to replace the found text with. For example, we can replace all occurrences of dog with cat using the following regular expression −

Live Demo
#/user/bin/perl

$string = "The cat sat on the mat";
$string =~ s/cat/dog/;

print "$string\n";
When above program is executed, it produces the following result −

The dog sat on the mat
Substitution Operator Modifiers
Here is the list of all the modifiers used with substitution operator.

Sr.No.	Modifier & Description
1	
i

Makes the match case insensitive.

2	
m

Specifies that if the string has newline or carriage return characters, the ^ and $ operators will now match against a newline boundary, instead of a string boundary.

3	
o

Evaluates the expression only once.

4	
s

Allows use of . to match a newline character.

5	
x

Allows you to use white space in the expression for clarity.

6	
g

Replaces all occurrences of the found expression with the replacement text.

7	
e

Evaluates the replacement as if it were a Perl statement, and uses its return value as the replacement text.

The Translation Operator
Translation is similar, but not identical, to the principles of substitution, but unlike substitution, translation (or transliteration) does not use regular expressions for its search on replacement values. The translation operators are −

tr/SEARCHLIST/REPLACEMENTLIST/cds
y/SEARCHLIST/REPLACEMENTLIST/cds
The translation replaces all occurrences of the characters in SEARCHLIST with the corresponding characters in REPLACEMENTLIST. For example, using the "The cat sat on the mat." string we have been using in this chapter −

Live Demo
#/user/bin/perl

$string = 'The cat sat on the mat';
$string =~ tr/a/o/;

print "$string\n";
When above program is executed, it produces the following result −

The cot sot on the mot.
Standard Perl ranges can also be used, allowing you to specify ranges of characters either by letter or numerical value. To change the case of the string, you might use the following syntax in place of the uc function.

$string =~ tr/a-z/A-Z/;
Translation Operator Modifiers
Following is the list of operators related to translation.

Sr.No.	Modifier & Description
1	
c

Complements SEARCHLIST.

2	
d

Deletes found but unreplaced characters.

3	
s

Squashes duplicate replaced characters.

The /d modifier deletes the characters matching SEARCHLIST that do not have a corresponding entry in REPLACEMENTLIST. For example −

Live Demo
#!/usr/bin/perl 

$string = 'the cat sat on the mat.';
$string =~ tr/a-z/b/d;

print "$string\n";
When above program is executed, it produces the following result −

b b   b.
The last modifier, /s, removes the duplicate sequences of characters that were replaced, so −

Live Demo
#!/usr/bin/perl

$string = 'food';
$string = 'food';
$string =~ tr/a-z/a-z/s;

print "$string\n";
When above program is executed, it produces the following result −

fod
More Complex Regular Expressions
You don't just have to match on fixed strings. In fact, you can match on just about anything you could dream of by using more complex regular expressions. Here's a quick cheat sheet −

Following table lists the regular expression syntax that is available in Python.

Sr.No.	Pattern & Description
1	
^

Matches beginning of line.

2	
$

Matches end of line.

3	
.

Matches any single character except newline. Using m option allows it to match newline as well.

4	
[...]

Matches any single character in brackets.

5	
[^...]

Matches any single character not in brackets.

6	
*

Matches 0 or more occurrences of preceding expression.

7	
+

Matches 1 or more occurrence of preceding expression.

8	
?

Matches 0 or 1 occurrence of preceding expression.

9	
{ n}

Matches exactly n number of occurrences of preceding expression.

10	
{ n,}

Matches n or more occurrences of preceding expression.

11	
{ n, m}

Matches at least n and at most m occurrences of preceding expression.

12	
a| b

Matches either a or b.

13	
\w

Matches word characters.

14	
\W

Matches nonword characters.

15	
\s

Matches whitespace. Equivalent to [\t\n\r\f].

16	
\S

Matches nonwhitespace.

17	
\d

Matches digits. Equivalent to [0-9].

18	
\D

Matches nondigits.

19	
\A

Matches beginning of string.

20	
\Z

Matches end of string. If a newline exists, it matches just before newline.

21	
\z

Matches end of string.

22	
\G

Matches point where last match finished.

23	
\b

Matches word boundaries when outside brackets. Matches backspace (0x08) when inside brackets.

24	
\B

Matches nonword boundaries.

25	
\n, \t, etc.

Matches newlines, carriage returns, tabs, etc.

26	
\1...\9

Matches nth grouped subexpression.

27	
\10

Matches nth grouped subexpression if it matched already. Otherwise refers to the octal representation of a character code.

28	
[aeiou]

Matches a single character in the given set

29	
[^aeiou]

Matches a single character outside the given set

The ^ metacharacter matches the beginning of the string and the $ metasymbol matches the end of the string. Here are some brief examples.

# nothing in the string (start and end are adjacent)
/^$/   

# a three digits, each followed by a whitespace
# character (eg "3 4 5 ")
/(\d\s) {3}/  

# matches a string in which every
# odd-numbered letter is a (eg "abacadaf")
/(a.)+/  

# string starts with one or more digits
/^\d+/

# string that ends with one or more digits
/\d+$/
Lets have a look at another example.

Live Demo
#!/usr/bin/perl

$string = "Cats go Catatonic\nWhen given Catnip";
($start) = ($string =~ /\A(.*?) /);
@lines = $string =~ /^(.*?) /gm;
print "First word: $start\n","Line starts: @lines\n";
When above program is executed, it produces the following result −

First word: Cats
Line starts: Cats When
Matching Boundaries
The \b matches at any word boundary, as defined by the difference between the \w class and the \W class. Because \w includes the characters for a word, and \W the opposite, this normally means the termination of a word. The \B assertion matches any position that is not a word boundary. For example −

/\bcat\b/ # Matches 'the cat sat' but not 'cat on the mat'
/\Bcat\B/ # Matches 'verification' but not 'the cat on the mat'
/\bcat\B/ # Matches 'catatonic' but not 'polecat'
/\Bcat\b/ # Matches 'polecat' but not 'catatonic'
Selecting Alternatives
The | character is just like the standard or bitwise OR within Perl. It specifies alternate matches within a regular expression or group. For example, to match "cat" or "dog" in an expression, you might use this −

if ($string =~ /cat|dog/)
You can group individual elements of an expression together in order to support complex matches. Searching for two people’s names could be achieved with two separate tests, like this −

if (($string =~ /Martin Brown/) ||  ($string =~ /Sharon Brown/))

This could be written as follows

if ($string =~ /(Martin|Sharon) Brown/)
Grouping Matching
From a regular-expression point of view, there is no difference between except, perhaps, that the former is slightly clearer.

$string =~ /(\S+)\s+(\S+)/;

and 

$string =~ /\S+\s+\S+/;
However, the benefit of grouping is that it allows us to extract a sequence from a regular expression. Groupings are returned as a list in the order in which they appear in the original. For example, in the following fragment we have pulled out the hours, minutes, and seconds from a string.

my ($hours, $minutes, $seconds) = ($time =~ m/(\d+):(\d+):(\d+)/);
As well as this direct method, matched groups are also available within the special $x variables, where x is the number of the group within the regular expression. We could therefore rewrite the preceding example as follows −

Live Demo
#!/usr/bin/perl

$time = "12:05:30";

$time =~ m/(\d+):(\d+):(\d+)/;
my ($hours, $minutes, $seconds) = ($1, $2, $3);

print "Hours : $hours, Minutes: $minutes, Second: $seconds\n";
When above program is executed, it produces the following result −

Hours : 12, Minutes: 05, Second: 30
When groups are used in substitution expressions, the $x syntax can be used in the replacement text. Thus, we could reformat a date string using this −

Live Demo
#!/usr/bin/perl

$date = '03/26/1999';
$date =~ s#(\d+)/(\d+)/(\d+)#$3/$1/$2#;

print "$date\n";
When above program is executed, it produces the following result −

1999/03/26
The \G Assertion
The \G assertion allows you to continue searching from the point where the last match occurred. For example, in the following code, we have used \G so that we can search to the correct position and then extract some information, without having to create a more complex, single regular expression −

Live Demo
#!/usr/bin/perl

$string = "The time is: 12:31:02 on 4/12/00";

$string =~ /:\s+/g;
($time) = ($string =~ /\G(\d+:\d+:\d+)/);
$string =~ /.+\s+/g;
($date) = ($string =~ m{\G(\d+/\d+/\d+)});

print "Time: $time, Date: $date\n";
When above program is executed, it produces the following result −

Time: 12:31:02, Date: 4/12/00
The \G assertion is actually just the metasymbol equivalent of the pos function, so between regular expression calls you can continue to use pos, and even modify the value of pos (and therefore \G) by using pos as an lvalue subroutine.

Regular-expression Examples
Literal Characters
Sr.No.	Example & Description
1	
Perl

Match "Perl".

Character Classes
Sr.No.	Example & Description
1	
[Pp]ython

Matches "Python" or "python"

2	
rub[ye]

Matches "ruby" or "rube"

3	
[aeiou]

Matches any one lowercase vowel

4	
[0-9]

Matches any digit; same as [0123456789]

5	
[a-z]

Matches any lowercase ASCII letter

6	
[A-Z]

Matches any uppercase ASCII letter

7	
[a-zA-Z0-9]

Matches any of the above

8	
[^aeiou]

Matches anything other than a lowercase vowel

9	
[^0-9]

Matches anything other than a digit

Special Character Classes
Sr.No.	Example & Description
1	
.

Matches any character except newline

2	
\d

Matches a digit: [0-9]

3	
\D

Matches a nondigit: [^0-9]

4	
\s

Matches a whitespace character: [ \t\r\n\f]

5	
\S

Matches nonwhitespace: [^ \t\r\n\f]

6	
\w

Matches a single word character: [A-Za-z0-9_]

7	
\W

Matches a nonword character: [^A-Za-z0-9_]

Repetition Cases
Sr.No.	Example & Description
1	
ruby?

Matches "rub" or "ruby": the y is optional

2	
ruby*

Matches "rub" plus 0 or more ys

3	
ruby+

Matches "rub" plus 1 or more ys

4	
\d{3}

Matches exactly 3 digits

5	
\d{3,}

Matches 3 or more digits

6.	
\d{3,5}

Matches 3, 4, or 5 digits

Nongreedy Repetition
This matches the smallest number of repetitions −

Sr.No.	Example & Description
1	
<.*>

Greedy repetition: matches "<python>perl>"

2	
<.*?>

Nongreedy: matches "<python>" in "<python>perl>"

Grouping with Parentheses
Sr.No.	Example & Description
1	
\D\d+

No group: + repeats \d

2	
(\D\d)+

Grouped: + repeats \D\d pair

3	
([Pp]ython(, )?)+

Match "Python", "Python, python, python", etc.

Backreferences
This matches a previously matched group again −

Sr.No.	Example & Description
1	
([Pp])ython&\1ails

Matches python&pails or Python&Pails

2	
(['"])[^\1]*\1

Single or double-quoted string. \1 matches whatever the 1st group matched. \2 matches whatever the 2nd group matched, etc.

Alternatives
Sr.No.	Example & Description
1	
python|perl

Matches "python" or "perl"

2	
rub(y|le))

Matches "ruby" or "ruble"

3	
Python(!+|\?)

"Python" followed by one or more ! or one ?

Anchors
This need to specify match positions.

Sr.No.	Example & Description
1	
^Python

Matches "Python" at the start of a string or internal line

2	
Python$

Matches "Python" at the end of a string or line

3	
\APython

Matches "Python" at the start of a string

4	
Python\Z

Matches "Python" at the end of a string

5	
\bPython\b

Matches "Python" at a word boundary

6	
\brub\B

\B is nonword boundary: match "rub" in "rube" and "ruby" but not alone

7	
Python(?=!)

Matches "Python", if followed by an exclamation point

8	
Python(?!!)

Matches "Python", if not followed by an exclamation point

Special Syntax with Parentheses
Sr.No.	Example & Description
1	
R(?#comment)

Matches "R". All the rest is a comment

2	
R(?i)uby

Case-insensitive while matching "uby"

3	
R(?i:uby)

Same as above

4	
rub(?:y|le))

Group only without creating \1 backreference
First: foo, Last: footbrdige