Introduction
Perl stands for Practical Extraction and Report Language. Invented by Larry Wall. It is not easy to learn. If you drive a car, you spent many weeks or months learning how,and then its easy to drive. When you’ve been programming Perl for about as many hours as it took you to learn to drive, Perl will be easy for you.
If you’re going to use a programming language for only a few minutes each week or month, you’d prefer one that is easier to learn,since you’ll have forgotten nearly all of it from one use to the next. Perl is for people who are programmers for at least 20 minutes per day, and probably most of that in Perl.
”’Hello World”’
#!/usr/bin/perl -w use strict; print "Hello World !\n";
As you noted there is no need of any main function in the source code. Perl script or program consists of one or more statements and ends with semicolon ;
Perl Documentation
apt-get install perl-doc. To use the online documentation use the command perldoc <doc-name>
* eg. $ perldoc perlintro
Library, Modules and packages:
”’CPAN:”’ comprehensive perl archive network
”’module”’: A file or a bundle of file which helps you to accomplish a task.
”’package”’: Its the another way to divide up a program. By using package, you can be sure that what you do in one section of your program does not affect another section. Whereas a module works with a file or bunch of files on your disk, a package is purely part of the source code.
Extension for Library: .pl
Extension for a module: .pm
”’Installing perl Module:”’
* perl -MCPAN -e shell
* cpan> install HTML::Template
Perl Variables Types:
Three Types of variables in perl
* Scalars
* Arrays
* Hashes
Scalar
A scalar represents a single value. A scalar value is either defined or undefined. If defined, it may hold a string, number, or reference. The only undefined value is undef. All other values are defined, even numeric and the empty string.
Declarations
In Perl, simple (scalar) variables have names beginning with a `$’ sign, followed by a varable name. The name
* must begin with a letter or an underscore (_);
* can contain after that any combination of letters, numbers, or the underscore;
* Declaring many variables at once my ($another, @array, %hash)
Numbers:
There are no integer value internal to perl All numbers are treated as floating point number.Floating point literals:
A literal is the way a value is represented in the source code of the perl program. A literal is not the result of a calculation or an I/O operation; it’s data written directly written into the source code.
Numbers with and without the decimal points are allowed, including leading plus or minus prefix as well as tracking number on a power of 10 with indicator E
eg.
1.23
-2.45
56e20 56 times 10 to the 20th power
etc
Integer Literals:
its straight forward.
-2
+300
359
3838398389398398
for clarity you can use underscore with the number.
eg. 23_399_383_333
It represents the same numbers.
Nondecimal Integer Literals:
Perl allows you to specify the numbers in other than base 10 (Decimal).
octal start with a leading 0
Hexadecimal start with a leading 0x
and binary with a leading 0b
02344
0x3ff
0b110101
Numeric operators:
Follow the same precedence as in C.
+
–
/
*
**
String
String are sequence of characters. Like numbers, strings have a literal representation, which is the way you represent the string in perl program. ”String are not array of characters in Perl” so you can’t use the array subscripting on a string to address one of its character; use substr for it.
Two different flavors.
• Single quoted string
• double quoted string
Single quoted string:
A sequence of characters enclosed in single quotes. The quote are not part of the string itself. They are just there to let perl identify the beginning and ending. Use backslash for printing or escaping the special symbol.
eg. print ‘this is new line of test \n’; \n is not interpreted as new line in single quote.
Double quoted String
have double quote. and can use \n, and escape seq. too as in C. like \t \r etc. another special feature of Double quoted strings is they are variable interpolated. Meaning that some variable name within the string is replaced with the value of variable.
String Operator
concatenation operator(. dot)—-> used to concatenate the string.
“hello” . “world” # same as “helloworld”
“hello” . ‘ ‘ . “world” # same as ‘hello world’
‘hello world’ . “\n” # same as “hello world\n”
String Repetition operator
Lower case letter x is used for it.
“fred” x 3 # is “fredfredfred”
“barney” x (4+1) # is “barney” × 5, or “barneybarneybarneybarneybarney”
5 × 4 # is really “5” × 4, which is “5555”
Quoting oeprator
The q// and qq// quoting operators allow arbitrary delimiters on interpolated and uninterpolated literals, respectively, corresponding to single- and double-quoted strings. For an uninterpolated string literal that contains single quotes, it’s easier to use q// than to escape all single quotes with backslashes:
$string = ‘Jon \’Maddog\’ Orwant’; # embedded single quotes
$string = q/Jon ‘Maddog’ Orwant/; # same thing, but more legible
Automatic conversion between string and number:
Perl will automatically convert between string and number depending upon the operator.
eg. “5” * 4 returns 20.
”’Comparison operator”’
*Comparison Numeric String
*Equal == eq
*Not equal != ne
*Less than < lt
*Greater than > gt
*Less than or equal to <= le
*Greater than or equal to >= ge
substr function
String are a basic data type; they aren’t array of a basic data type. Instead of using array subscripting to access individual characters as you sometimes do in other programming languages, in Perl you use functions like unpack or substr to access individual characters or a portion of the string. The substr function lets you read from and write to specific portions of the string.
$string = “This is what you have”; # +012345678901234567890 Indexing forwards (left to right)
# 109876543210987654321- Indexing backwards (right to left)
# note that 0 means 10 or 20, etc. above
$first = substr($string, 0, 1); # “T”
$start = substr($string, 5, 2); # “is”
$rest = substr($string, 13); # “you have”
$last = substr($string, -1); # “e”
$end = substr($string, -4); # “have”
$piece = substr($string, -8, 3); # “you”
substring is also used to replace a portion of the string
This is what you have”; print $string;
This is what you have
substr($string, 5, 2) = “wasn’t”; # change “is” to “wasn’t”
Arrays
If scalar is singular in perl then plural in perl are arrays and lists. A list is an ordered collection of scalars. An array is a variable that contains a list. In perl the two terms are used interchangeably, but to be accurate list is the data and array is the variable.
Declaration:
my @array = ( 2, 3, daya, maya, 6 )
when you use the use strict this syntax may be wrong, as having both number and name.
accessing the arrary variable:
$arrary[3]—> 3rd element
For acessing the whole array element, print @array
There are special array eg.
my @sorted = sort @arrary;
my @backwards = reverse @numbers;
etc
”’Array Indices:”’
Last index of the Array can be retrieved by $#<array-name>
* eg. $end = $#rocks;
The array size is dynamic, you don’t have to specify the size of the array. It automatically adjust depending upon your uses.There is no limit on its length as long as there is available memory.
-ve index:
* -1 index is used to access the last element of the array.
eg.
#!/usr/bin/perl
use strict;
my @var = (2,3,4,5,”daya”,”maya”,”test”,6827);
print “@var\n”;
print “The 3rd variable is: $var[3]\n”;
my $lastindex = $#var;
print “The last element is:$var[$lastindex]\n”;
print “the -2 index element: $var[-2]\n”;</pre>
”’qw shortcut (Quoted words)”’
We frequently needs the list of words, the qw shortcut helps us to generate the list without typing a lot of extra quote marks.
* @listvar = (“daya”, “maya”, “test”, “ole”, “linux”);
* @listvar = qw(daya maya test ole linux); separate each of the element with the space bar.
”’range operator”’
(1..100) ===1 to 100.
”’List Assignment:”’
In much the same way as the scalar values are assigned to variable, list value may be also assigned to variables.
eg.
($name, $month, $salary) = qw(hari, feb, 5600);
Its very easy to swap in perl unlike in other language such as C which needs the temporary variables.
($var1, $var2) = ($var2, $var1);
it swaps the value of var1 and var2.
Note:
* $calar
* @rray
* To retrieve whole array , @array-name
* @array1 = @arrya2 —> copy one array to another.
”’Pop and Push Operators”’
* Helps to add and retrieve the array elements without using index.
* pop operator takes the last element of the array and returns it.
* push operator adds an element (or a list of elements) to the end of the array.
@array = 1..10
$var1 = pop(@array); #gets 10
$var2 = pop(@array); #get 9
push(@array,100); #push 100 to the end of the array.
push(@array, @others);
”’The shift and unshift Operators”’
It works in the same way as the push and pop but unlike push and pop does the operation at the end of the array or list it does at the beginning.
@array = 1..10
$var1 = shift@array; #gets 1
$var2 = shift@array; #gets 2
unshift(@array,5); # insert 5 at the beginning of the array
”’foreach control structure”’
The foreach loop steps through a list of values, executing one iteration for each value. foreach statement can be used in two ways.
1. using another variable to retrieve the element.
foreach $i (@array) {
print “$i”;
—-
}
2.Using Perl default variable $_ to retrieve element.
foreach (@array)
{
print “$_\n”;
—-
}
</pre>
”’Special Array Operator”’
* sort operator
@sort = sort(@array); #sorts only the string.
* reverse operator
@rev = reverse(@array);
==scalar and list context==
The most important things to understand. The context refers to where an expression is found. As Perl is parsing your expressions,it always expects either a scalar value or a list value.* What Perl expects is called the context of the expression.
42 + something # The something must be a scalar
sort something # The something must be a list
@people = qw( fred barney betty );
@sorted = sort @people; # list context: barney, betty, fred
$number = 42 + @people; # scalar context: 42 + 3 gives 45
Even ordinary assignment (to a scalar or a list) causes different contexts:
@list = @people; # a list of three people
$n = @people; # the number 3
”’example”’
#!/usr/bin/perl -w
use strict;
sub test {
my($num1) = @_; #list context
my $num2 = @_; #Scalar Context, no of array elements.
print “The num1 is $num1\n”;
print “The num2 is $num2\n”;
}
Forcing Scalar Context
On occasion, you may need to force scalar context where Perl is expecting a list. In that
case, you can use the fake function scalar. It’s not a true function because it just tells
Perl to provide a scalar context:
@rocks = qw( talc quartz jade obsidian );
print “How many rocks do you have?\n”;
print “I have “, @rocks, ” rocks!\n”; # WRONG, prints names of rocks
print “I have “, scalar @rocks, ” rocks!\n”; # Correct, gives a number
Oddly enough, there’s no corresponding function to force list context.
”’Using List-Producing Expressions in Scalar Context”’
$fred = something; # scalar context
@pebbles = something; # list context
($wilma, $betty) = something; # list context
($dino) = something; # still list context!
Don’t be fooled by the one-element list; that last one is a list context, not a scalar one.The parentheses are significant here, making the fourth of those different than the first.
”'<STDIN> in List Context”’
@lines = <STDIN>; # read standard input in list context
press CTRL-D at the last for the end of the input.
@lines = <STDIN>; # Read all the lines
chomp(@lines); # discard all the newline characters
But the more common way to write that is with code similar to what we used earlier:
chomp(@lines = <STDIN>); # Read the lines, not the newlines
The defined function
The line input operator <STDIN> is one operator that can return undef. Normally it returns the line of text , but some time it can return undef value when there is no more input such as End of File (Ctrl -D signal an eg). To tell whether a value is undef and not the empty string, use the defined function, which returns false for undef, and true for everything else:
eg.
daya@debian:/tmp$ cat t2.pl
my $test = <stdin>;
#my $test = undef;
if (defined($test)) {
print “The input is $test”;
}
else{
print “No input is available:\n”;
}
If the program is run and press Ctrl-D then it will print no input is available. The else statement.