Updated April 8, 2023
Introduction to Perl Commands
Perl is a programming language. Earlier designed for text editing only, it is now used for many purposes like System administration in Linux, web development, network programming, etc. The chief architect and creator of Perl are Larry Wall. It was created back in 1987 and is still used as a major programming language. Perl is a high-level language. It is also an interpreted and dynamic programming language. Now we will learn Perl Commands in detail.
Basic Perl Commands
The basic commands are as explained below.
1. Basic Perl Command to print in Perl
#!/usr/bin/perl
# This will print "Hello, World"
print "Hello, world\n";
2. Single line comment in Perl
#!/usr/bin/perl
# This is a single line comment
print "Hello Perl\n";
3. Multiple line comment in Perl
#!/usr/bin/perl
=begin comment
This is a multiline comment.
Line 1
Line 2
Line 3
We can insert
as much lines
as comments
until we code =cut
to end multiline comments
=cut
print "Hello Perl\n";
4. Variable assignment in Perl (Interpolation of double-quoted variables)
#!/usr/bin/perl
$a = 10;
print "Variable a = $a\n";
5. Escape character in Perl
#!/usr/bin/perl
$a = "This is \"Perl\"";
print "$a\n";
print "\$a\n";
6. In Perl, strings have different behavior with double quotes and single quotes. While double quotes allow interpolation, single quotes don’t.
#!/usr/bin/perl
# Interpolation example.
$str = "Hello \nPerl";
print "$str\n";
# Non-interpolation example.
$str = 'Hello \nPerl';
print "$str\n";
7. Upper Case in Perl Command
#!/usr/bin/perl
# Only u will become upper case.
$str = "\uhello perl";
print "$str\n";
# All the letters will become Uppercase.
$str = "\Uhello perl";
print "$str\n";
# A portion of string will become Uppercase.
$str = "hello \Uperl\E";
print "$str\n";
8. Scalar Variable assignment in Perl
#!/usr/bin/perl
$age = 35; # Assigning an integer
$name = "Tony Stark"; # Assigning a string
$pi = 3.14; # Assigning a floating point
print "Age = $age\n";
print "Name = $name\n";
print "Pi = $pi\n";
9. Simple scalar operations in Perl
#!/usr/bin/perl
$constr = "hi" . "perl";# Concatenates two or more strings.
$add = 40 + 10; # addition of two numbers.
$prod = 4 * 51;# multiplication of two numbers.
$connumstr = $constr . $add;# concatenation of string and number.
print "str = $constr\n";
print "num = $add\n";
print "mul = $prod\n";
print "mix = $connumstr\n";
10. Special Literals in Perl
#!/usr/bin/perl
print "Current file name ". __FILENAME__ . "\n";
print "Current Line Number " . __LINENO__ ."\n";
print "Current Package " . __PACKAGENAME__ ."\n";
# here they cannot be interpolated
print "__FILENAME__ __LINENO__ __PACKAGENAME__\n";
Intermediate Perl Commands
The intermediate commands are as explained below.
1. Arrays in Perl
Array index starts from 0. The negative index indicates elements from the last position. Example below.
#!/usr/bin/perl
@weekday = qw/Mon Tue Wed Thu Fri Sat Sun/;
print "$weekday[0]\n";
print "$weekday[1]\n";
print "$weekday[2]\n";
print "$weekday[6]\n";
print "$weekday[-1]\n";
print "$weekday[-6]\n";
2. Arrays for elements in a sequence
#!/usr/bin/perl
@oneToTen = (1..10);
@fiftyToSeventyfive = (50..75);
@aToZ = (a..z);
print "@oneToTen\n"; # Prints one to ten
print "@fiftyToSeventyfive\n"; # Prints fifty to seventy five
print "@aToZ\n"; # Prints from a to z
3. Array element addition and removal
#!/usr/bin/perl
# creating an array
@expression = ("happy","sad","angry");
print "1. \@expression = @expression\n";
# add element to the end of the arraypush(@expression, "jolly");
print "2. \@expression = @expression\n";
# add element to the beginning of the arrayunshift(@expression, "excited");
print "3. \@expression = @expression\n";
# remove element to the last of the array.pop(@expression);
print "4. \@expression = @expression\n";
# remove element from the beginning of the array.shift(@expression);
print "5. \@expression = @expression\n";
4. Hashes in Perl
Hash is a concept of Key Value Pair. Below is an example to create a hash.
#!/usr/bin/perl
%data = ('Mohan Singh' => 55, 'Ram Gupta' => 25, 'Bhuvan Kumar' => 31);
@age = values %data;
print "$age[0]\n";
print "$age[1]\n";
print "$age[2]\n";
5. Hash element addition and removal
#!/usr/bin/perl
%data = ('Mohan Singh' => 55, 'Ram Gupta' => 25, 'Bhuvan Kumar' => 31);
@keys = keys %data;
$size = @keys;
print "a - Hash size: $size\n";
# add an element to the hash;
$data{'Imran Khan'} = 44;
@keys = keys %data;
$size = @keys;
print "b - Hash size: $size\n";
# delete an element from the hash;
delete $data{'Imran Khan'};
@keys = keys %data;
$size = @keys;
print "c - Hash size: $size\n";
6. Conditional Statement in Perl: if…elsif…else
#!/usr/local/bin/perl
$num = 50;
# check condition using if statement
if( $num == 40 ) {
# print the following if true
printf "num has a value which is 20\n";
} elsif( $num == 60 ) {
# else print if the next condition is true
printf "num has a value which is 30\n";
} else {
# if none is true print following
printf "num has a value which is $num\n";
}
7. Conditional Statement in Perl : unless…elsif…else statement
#!/usr/local/bin/perl,
$num = 50;
# check condition using unless statement
unless( $num == 25) {
# if condition is false then print the following
printf "num has a value which is not 25\n";
} elsif( $num == 55) {
# if condition is true then print the following
printf "num has a value which is 55";
} else {
# if both the condition is dissatisfied, print the
original value
printf "num has a value which is $num\n";
}
8. Loops in Perl: While loop
#!/usr/local/bin/perl
$i = 1;
# while loop
while( $i < 5 ) {
printf "Value of i: $i\n";
$i = $i + 1;
}
9. Loops in Perl: Until Loop and For Loop
#!/usr/local/bin/perl
$i = 1;
# until loop
until( $i > 5 ) {
printf "Value of i: $i\n";
$i = $i + 1;
}
# for loop
for ($j = 0; $j < 3; $j++) {
printf "Value of j: $j\n";
}
10. Loops in Perl: do…while Loop
#!/usr/local/bin/perl
$i = 10;
# do...while loop
do{
printf "Value of i: $i\n";
$i = $i + 1;
}
while( $i < 20 );
Advanced Perl Commands
The advanced commands are as explained below.
1. Socket Programming in Perl: Server
#!/usr/bin/perl -w
# Filename : server.pl
use strict;
use Socket;
# use port 8081 as default
my $port = shift || 8081;
my $protocol = getprotobyname('tcp');
my $server = "localhost"; # Host IP running the
server
# create a socket, make it reusable
socket(SOCKET, PF_INET, SOCK_STREAM,
$protocol)
or die "Can't open socket $!\n";
setsockopt(SOCKET, SOL_SOCKET,
SO_REUSEADDR, 1)
or die "Can't set socket option to SO_REUSEADDR
$!\n";
# bind to a port, then listen
bind( SOCKET, pack_sockaddr_in($port,
inet_aton($server)))
or die "Can't bind to port $port! \n";
listen(SOCKET, 5) or die "listen: $!";
print "SERVER started on port $port\n";
# accepting a connection
my $client_addr;
while ($client_addr = accept(NEW_SOCKET,
SOCKET)) {
# send them a message, close connection
my $name = gethostbyaddr($client_addr,
AF_INET );
print NEW_SOCKET "Smile from the server";
print "Connection recieved from $name\n";
close NEW_SOCKET;
}
2. Socket Programming in Perl: Client
!/usr/bin/perl -w
# Filename : client.pl
use strict;
use Socket;
# initialize host and port
my $host = shift || 'localhost';
my $port = shift || 8081;
my $server = "localhost"; # Host IP running the
server
# create the socket, connect to the port
socket(SOCKET,PF_INET,SOCK_STREAM,(getproto
byname('tcp'))[2])
or die "Can't create a socket $!\n";
connect( SOCKET, pack_sockaddr_in($port,
inet_aton($server)))
or die "Can't connect to port $port! \n";
my $line;
while ($line = <SOCKET>) {
print "$line\n";
}close SOCKET or die "close: $!";
3. Database connectivity using Perl
#!/usr/bin/per
use DBI
use strict;
my $driver = "mysql";
my $database = "DBTEST";
my $dsn = "DBI:$driver:database=$database";
my $userid = "user123";
my $password = "pass123";
my $dbh = DBI->connect($dsn, $userid, $password
) or die $DBI::errstr;
4. CGI Programming using Perl
#!/usr/bin/perl
print "Content-type:text/html\r\n\r\n";
print '<html>';
print '<head>';
print '<title>Hello Perl - CGI Example</title>';
print '</head>';
print '<body>';
print '<h2>Hello Perl! This is a CGI program example</h2>';
print '</body>';
print '</html>';
1;
Tips and Tricks
Perl is said to be a mixture of all the languages, i.e., it comes equipped with the best features of major programming languages. The most important aspect is to master the basics and proceed with the practice of this language. Upgradation and self-improvement is the key to success.
Conclusion
The above programs are samples which will help an entity to understand the basics and proceed with self-enhancement. This has been said an ugly programming language, but actually, it showcases a wide variety of features. It is recommended to follow this document to compile codes and understand what is happening in the program itself.
Recommended Articles
This has been a guide to Perl Commands. Here we have discussed basic, intermediate as well as advanced Perl Commands along with tips and tricks to use. You may also look at the following article to learn more-