Perl – Quick Guide ”; Previous Next Perl – Introduction Perl is a general-purpose programming language originally developed for text manipulation and now used for a wide range of tasks including system administration, web development, network programming, GUI development, and more. What is Perl? Perl is a stable, cross platform programming language. Though Perl is not officially an acronym but few people used it as Practical Extraction and Report Language. It is used for mission critical projects in the public and private sectors. Perl is an Open Source software, licensed under its Artistic License, or the GNU General Public License (GPL). Perl was created by Larry Wall. Perl 1.0 was released to usenet”s alt.comp.sources in 1987. At the time of writing this tutorial, the latest version of perl was 5.16.2. Perl is listed in the Oxford English Dictionary. PC Magazine announced Perl as the finalist for its 1998 Technical Excellence Award in the Development Tool category. Perl Features Perl takes the best features from other languages, such as C, awk, sed, sh, and BASIC, among others. Perls database integration interface DBI supports third-party databases including Oracle, Sybase, Postgres, MySQL and others. Perl works with HTML, XML, and other mark-up languages. Perl supports Unicode. Perl is Y2K compliant. Perl supports both procedural and object-oriented programming. Perl interfaces with external C/C++ libraries through XS or SWIG. Perl is extensible. There are over 20,000 third party modules available from the Comprehensive Perl Archive Network (CPAN). The Perl interpreter can be embedded into other systems. Perl and the Web Perl used to be the most popular web programming language due to its text manipulation capabilities and rapid development cycle. Perl is widely known as “the duct-tape of the Internet“. Perl can handle encrypted Web data, including e-commerce transactions. Perl can be embedded into web servers to speed up processing by as much as 2000%. Perl”s mod_perl allows the Apache web server to embed a Perl interpreter. Perl”s DBI package makes web-database integration easy. Perl is Interpreted Perl is an interpreted language, which means that your code can be run as is, without a compilation stage that creates a non portable executable program. Traditional compilers convert programs into machine language. When you run a Perl program, it”s first compiled into a byte code, which is then converted ( as the program runs) into machine instructions. So it is not quite the same as shells, or Tcl, which are strictly interpreted without an intermediate representation. It is also not like most versions of C or C++, which are compiled directly into a machine dependent format. It is somewhere in between, along with Python and awk and Emacs .elc files. Perl – Environment Before we start writing our Perl programs, let”s understand how to setup our Perl environment. Perl is available on a wide variety of platforms − Unix (Solaris, Linux, FreeBSD, AIX, HP/UX, SunOS, IRIX etc.) Win 9x/NT/2000/ WinCE Macintosh (PPC, 68K) Solaris (x86, SPARC) OpenVMS Alpha (7.2 and later) Symbian Debian GNU/kFreeBSD MirOS BSD And many more… This is more likely that your system will have perl installed on it. Just try giving the following command at the $ prompt − $perl -v If you have perl installed on your machine, then you will get a message something as follows − This is perl 5, version 16, subversion 2 (v5.16.2) built for i686-linux Copyright 1987-2012, Larry Wall Perl may be copied only under the terms of either the Artistic License or the GNU General Public License, which may be found in the Perl 5 source kit. Complete documentation for Perl, including FAQ lists, should be found on this system using “man perl” or “perldoc perl”. If you have access to the Internet, point your browser at http://www.perl.org/, the Perl Home Page. If you do not have perl already installed, then proceed to the next section. Getting Perl Installation The most up-to-date and current source code, binaries, documentation, news, etc. are available at the official website of Perl. Perl Official Website − https://www.perl.org/ You can download Perl documentation from the following site. Perl Documentation Website − https://perldoc.perl.org Install Perl Perl distribution is available for a wide variety of platforms. You need to download only the binary code applicable for your platform and install Perl. If the binary code for your platform is not available, you need a C compiler to compile the source code manually. Compiling the source code offers more flexibility in terms of choice of features that you require in your installation. Here is a quick overview of installing Perl on various platforms. Unix and Linux Installation Here are the simple steps to install Perl on Unix/Linux machine. Open a Web browser and go to https://www.perl.org/get.html. Follow the link to download zipped source code available for Unix/Linux. Download perl-5.x.y.tar.gz file and issue the following commands at $ prompt. $tar -xzf perl-5.x.y.tar.gz $cd perl-5.x.y $./Configure -de $make $make test $make install NOTE − Here $ is a Unix prompt where you type your command, so make sure you are not typing $ while typing the above mentioned commands. This will install Perl in a standard location /usr/local/bin and its libraries are installed in /usr/local/lib/perlXX, where XX is the version of Perl that you are using. It will take a while to compile the source code after issuing the make command. Once installation is done, you can issue perl -v command at $ prompt to check perl installation. If everything is fine, then it will display message like we have shown above. Windows Installation Here are the steps to install Perl on Windows machine. Follow the link for the Strawberry Perl installation on Windows http://strawberryperl.com Download either 32bit or 64bit version of installation. Run the downloaded file by double-clicking it in Windows Explorer. This brings up the Perl install wizard, which is really easy to use. Just accept the default settings, wait until the installation is finished, and you”re ready to roll! Macintosh Installation In order to build your own version of
Category: perl
Perl – Socket Programming
Perl – Socket Programming ”; Previous Next What is a Socket? Socket is a Berkeley UNIX mechanism of creating a virtual duplex connection between different processes. This was later ported on to every known OS enabling communication between systems across geographical location running on different OS software. If not for the socket, most of the network communication between systems would never ever have happened. Taking a closer look; a typical computer system on a network receives and sends information as desired by the various applications running on it. This information is routed to the system, since a unique IP address is designated to it. On the system, this information is given to the relevant applications, which listen on different ports. For example an internet browser listens on port 80 for information received from the web server. Also we can write our custom applications which may listen and send/receive information on a specific port number. For now, let”s sum up that a socket is an IP address and a port, enabling connection to send and recieve data over a network. To explain above mentioned socket concept we will take an example of Client – Server Programming using Perl. To complete a client server architecture we would have to go through the following steps − To Create a Server Create a socket using socket call. Bind the socket to a port address using bind call. Listen to the socket at the port address using listen call. Accept client connections using accept call. To Create a Client Create a socket with socket call. Connect (the socket) to the server using connect call. Following diagram shows the complete sequence of the calls used by Client and Server to communicate with each other − Server Side Socket Calls The socket() call The socket() call is the first call in establishing a network connection is creating a socket. This call has the following syntax − socket( SOCKET, DOMAIN, TYPE, PROTOCOL ); The above call creates a SOCKET and other three arguments are integers which should have the following values for TCP/IP connections. DOMAIN should be PF_INET. It”s probable 2 on your computer. TYPE should be SOCK_STREAM for TCP/IP connection. PROTOCOL should be (getprotobyname(”tcp”))[2]. It is the particular protocol such as TCP to be spoken over the socket. So socket function call issued by the server will be something like this − use Socket # This defines PF_INET and SOCK_STREAM socket(SOCKET,PF_INET,SOCK_STREAM,(getprotobyname(”tcp”))[2]); The bind() call The sockets created by socket() call are useless until they are bound to a hostname and a port number. Server uses the following bind() function to specify the port at which they will be accepting connections from the clients. bind( SOCKET, ADDRESS ); Here SOCKET is the descriptor returned by socket() call and ADDRESS is a socket address ( for TCP/IP ) containing three elements − The address family (For TCP/IP, that”s AF_INET, probably 2 on your system). The port number (for example 21). The internet address of the computer (for example 10.12.12.168). As the bind() is used by a server, which does not need to know its own address so the argument list looks like this − use Socket # This defines PF_INET and SOCK_STREAM $port = 12345; # The unique port used by the sever to listen requests $server_ip_address = “10.12.12.168”; bind( SOCKET, pack_sockaddr_in($port, inet_aton($server_ip_address))) or die “Can”t bind to port $port! n”; The or die clause is very important because if a server dies without outstanding connections, the port won”t be immediately reusable unless you use the option SO_REUSEADDR using setsockopt() function. Here pack_sockaddr_in() function is being used to pack the Port and IP address into binary format. The listen() call If this is a server program, then it is required to issue a call to listen() on the specified port to listen, i.e., wait for the incoming requests. This call has the following syntax − listen( SOCKET, QUEUESIZE ); The above call uses SOCKET descriptor returned by socket() call and QUEUESIZE is the maximum number of outstanding connection request allowed simultaneously. The accept() call If this is a server program then it is required to issue a call to the access() function to accept the incoming connections. This call has the following syntax − accept( NEW_SOCKET, SOCKET ); The accept call receive SOCKET descriptor returned by socket() function and upon successful completion, a new socket descriptor NEW_SOCKET is returned for all future communication between the client and the server. If access() call fails, then it returns FLASE which is defined in Socket module which we have used initially. Generally, accept() is used in an infinite loop. As soon as one connection arrives the server either creates a child process to deal with it or serves it himself and then goes back to listen for more connections. while(1) { accept( NEW_SOCKET, SOCKT ); ……. } Now all the calls related to server are over and let us see a call which will be required by the client. Client Side Socket Calls The connect() call If you are going to prepare client program, then first you will use socket() call to create a socket and then you would have to use connect() call to connect to the server. You already have seen socket() call syntax and it will remain similar to server socket() call, but here is the syntax for connect() call − connect( SOCKET, ADDRESS ); Here SCOKET is the socket descriptor returned by socket() call issued by the client and ADDRESS is a socket address similar to bind call, except that it contains the IP address of the remote server. $port = 21; # For example, the ftp port $server_ip_address = “10.12.12.168”; connect( SOCKET, pack_sockaddr_in($port, inet_aton($server_ip_address))) or die “Can”t connect to port $port! n”; If you connect to the server successfully, then you can start sending your commands to the server using SOCKET descriptor, otherwise your client will come out by giving an error message. Client – Server Example Following is a Perl code to
Perl – CGI Programming
Perl – CGI Programming ”; Previous Next What is CGI ? A Common Gateway Interface, or CGI, is a set of standards that defines how information is exchanged between the web server and a custom script. The CGI specs are currently maintained by the NCSA and NCSA defines CGI is as follows − The Common Gateway Interface, or CGI, is a standard for external gateway programs to interface with information servers such as HTTP servers. The current version is CGI/1.1 and CGI/1.2 is under progress. Web Browsing To understand the concept of CGI, lets see what happens when we click a hyper link available on a web page to browse a particular web page or URL. Your browser contacts web server using HTTP protocol and demands for the URL, i.e., web page filename. Web Server will check the URL and will look for the filename requested. If web server finds that file then it sends the file back to the browser without any further execution otherwise sends an error message indicating that you have requested a wrong file. Web browser takes response from web server and displays either the received file content or an error message in case file is not found. However, it is possible to set up HTTP server in such a way so that whenever a file in a certain directory is requested that file is not sent back; instead it is executed as a program, and whatever that program outputs as a result, that is sent back for your browser to display. This can be done by using a special functionality available in the web server and it is called Common Gateway Interface or CGI and such programs which are executed by the server to produce final result, are called CGI scripts. These CGI programs can be a PERL Script, Shell Script, C or C++ program, etc. CGI Architecture Diagram Web Server Support and Configuration Before you proceed with CGI Programming, make sure that your Web Server supports CGI functionality and it is configured to handle CGI programs. All the CGI programs to be executed by the web server are kept in a pre-configured directory. This directory is called CGI directory and by convention it is named as /cgi-bin. By convention Perl CGI files will have extention as .cgi. First CGI Program Here is a simple link which is linked to a CGI script called hello.cgi. This file has been kept in /cgi-bin/ directory and it has the following content. Before running your CGI program, make sure you have change mode of file using chmod 755 hello.cgi UNIX command. #!/usr/bin/perl print “Content-type:text/htmlrnrn”; print ”<html>”; print ”<head>”; print ”<title>Hello Word – First CGI Program</title>”; print ”</head>”; print ”<body>”; print ”<h2>Hello Word! This is my first CGI program</h2>”; print ”</body>”; print ”</html>”; 1; Now if you click hello.cgi link then request goes to web server who search for hello.cgi in /cgi-bin directory, execute it and whatever result got generated, web server sends that result back to the web browser, which is as follows − Hello Word! This is my first CGI program This hello.cgi script is a simple Perl script which is writing its output on STDOUT file, i.e., screen. There is one important and extra feature available which is first line to be printed Content-type:text/htmlrnrn. This line is sent back to the browser and specifies the content type to be displayed on the browser screen. Now you must have undertood basic concept of CGI and you can write many complicated CGI programs using Perl. This script can interact with any other exertnal system also to exchange information such as a database, web services, or any other complex interfaces. Understanding HTTP Header The very first line Content-type:text/htmlrnrn is a part of HTTP header, which is sent to the browser so that browser can understand the incoming content from server side. All the HTTP header will be in the following form − HTTP Field Name: Field Content For Example − Content-type:text/htmlrnrn There are few other important HTTP headers, which you will use frequently in your CGI Programming. Sr.No. Header & Description 1 Content-type: String A MIME string defining the format of the content being returned. Example is Content-type:text/html 2 Expires: Date String The date when the information becomes invalid. This should be used by the browser to decide when a page needs to be refreshed. A valid date string should be in the format 01 Jan 1998 12:00:00 GMT. 3 Location: URL String The URL that should be returned instead of the URL requested. You can use this filed to redirect a request to any other location. 4 Last-modified: String The date of last modification of the file. 5 Content-length: String The length, in bytes, of the data being returned. The browser uses this value to report the estimated download time for a file. 6 Set-Cookie: String Set the cookie passed through the string CGI Environment Variables All the CGI program will have access to the following environment variables. These variables play an important role while writing any CGI program. Sr.No. Variables Names & Description 1 CONTENT_TYPE The data type of the content. Used when the client is sending attached content to the server. For example file upload, etc. 2 CONTENT_LENGTH The length of the query information. It”s available only for POST requests 3 HTTP_COOKIE Returns the set cookies in the form of key & value pair. 4 HTTP_USER_AGENT The User-Agent request-header field contains information about the user agent originating the request. Its name of the web browser. 5 PATH_INFO The path for the CGI script. 6 QUERY_STRING The URL-encoded information that is sent with GET method request. 7 REMOTE_ADDR The IP address of the remote host making the request. This can be useful for logging or for authentication purpose. 8 REMOTE_HOST The fully qualified name of the host making the request. If this information is not available then REMOTE_ADDR can be used to get IR address. 9 REQUEST_METHOD The method used to make the
Perl – Object Oriented
Object Oriented Programming in PERL ”; Previous Next We have already studied references in Perl and Perl anonymous arrays and hashes. Object Oriented concept in Perl is very much based on references and anonymous array and hashes. Let”s start learning basic concepts of Object Oriented Perl. Object Basics There are three main terms, explained from the point of view of how Perl handles objects. The terms are object, class, and method. An object within Perl is merely a reference to a data type that knows what class it belongs to. The object is stored as a reference in a scalar variable. Because a scalar only contains a reference to the object, the same scalar can hold different objects in different classes. A class within Perl is a package that contains the corresponding methods required to create and manipulate objects. A method within Perl is a subroutine, defined with the package. The first argument to the method is an object reference or a package name, depending on whether the method affects the current object or the class. Perl provides a bless() function, which is used to return a reference which ultimately becomes an object. Defining a Class It is very simple to define a class in Perl. A class is corresponding to a Perl Package in its simplest form. To create a class in Perl, we first build a package. A package is a self-contained unit of user-defined variables and subroutines, which can be re-used over and over again. Perl Packages provide a separate namespace within a Perl program which keeps subroutines and variables independent from conflicting with those in other packages. To declare a class named Person in Perl we do − package Person; The scope of the package definition extends to the end of the file, or until another package keyword is encountered. Creating and Using Objects To create an instance of a class (an object) we need an object constructor. This constructor is a method defined within the package. Most programmers choose to name this object constructor method new, but in Perl you can use any name. You can use any kind of Perl variable as an object in Perl. Most Perl programmers choose either references to arrays or hashes. Let”s create our constructor for our Person class using a Perl hash reference. When creating an object, you need to supply a constructor, which is a subroutine within a package that returns an object reference. The object reference is created by blessing a reference to the package”s class. For example − package Person; sub new { my $class = shift; my $self = { _firstName => shift, _lastName => shift, _ssn => shift, }; # Print all the values just for clarification. print “First Name is $self->{_firstName}n”; print “Last Name is $self->{_lastName}n”; print “SSN is $self->{_ssn}n”; bless $self, $class; return $self; } Now Let us see how to create an Object. $object = new Person( “Mohammad”, “Saleem”, 23234345); You can use simple hash in your consturctor if you don”t want to assign any value to any class variable. For example − package Person; sub new { my $class = shift; my $self = {}; bless $self, $class; return $self; } Defining Methods Other object-oriented languages have the concept of security of data to prevent a programmer from changing an object data directly and they provide accessor methods to modify object data. Perl does not have private variables but we can still use the concept of helper methods to manipulate object data. Lets define a helper method to get person’s first name − sub getFirstName { return $self->{_firstName}; } Another helper function to set person’s first name − sub setFirstName { my ( $self, $firstName ) = @_; $self->{_firstName} = $firstName if defined($firstName); return $self->{_firstName}; } Now lets have a look into complete example: Keep Person package and helper functions into Person.pm file. #!/usr/bin/perl package Person; sub new { my $class = shift; my $self = { _firstName => shift, _lastName => shift, _ssn => shift, }; # Print all the values just for clarification. print “First Name is $self->{_firstName}n”; print “Last Name is $self->{_lastName}n”; print “SSN is $self->{_ssn}n”; bless $self, $class; return $self; } sub setFirstName { my ( $self, $firstName ) = @_; $self->{_firstName} = $firstName if defined($firstName); return $self->{_firstName}; } sub getFirstName { my( $self ) = @_; return $self->{_firstName}; } 1; Now let”s make use of Person object in employee.pl file as follows − #!/usr/bin/perl use Person; $object = new Person( “Mohammad”, “Saleem”, 23234345); # Get first name which is set using constructor. $firstName = $object->getFirstName(); print “Before Setting First Name is : $firstNamen”; # Now Set first name using helper function. $object->setFirstName( “Mohd.” ); # Now get first name set by helper function. $firstName = $object->getFirstName(); print “Before Setting First Name is : $firstNamen”; When we execute above program, it produces the following result − First Name is Mohammad Last Name is Saleem SSN is 23234345 Before Setting First Name is : Mohammad Before Setting First Name is : Mohd. Inheritance Object-oriented programming has very good and useful concept called inheritance. Inheritance simply means that properties and methods of a parent class will be available to the child classes. So you don”t have to write the same code again and again, you can just inherit a parent class. For example, we can have a class Employee, which inherits from Person. This is referred to as an “isa” relationship because an employee is a person. Perl has a special variable, @ISA, to help with this. @ISA governs (method) inheritance. Following are the important points to be considered while using inheritance − Perl searches the class of the specified object for the given method or attribute, i.e., variable. Perl searches the classes defined in the object class”s @ISA array. If no method is found in steps 1 or 2, then Perl uses an AUTOLOAD subroutine, if one is found in the @ISA tree. If a matching method still cannot be found, then
Perl – Sending Email
Perl – Sending Email ”; Previous Next Using sendmail Utility Sending a Plain Message If you are working on Linux/Unix machine then you can simply use sendmail utility inside your Perl program to send email. Here is a sample script that can send an email to a given email ID. Just make sure the given path for sendmail utility is correct. This may be different for your Linux/Unix machine. #!/usr/bin/perl $to = ”[email protected]”; $from = ”[email protected]”; $subject = ”Test Email”; $message = ”This is test email sent by Perl Script”; open(MAIL, “|/usr/sbin/sendmail -t”); # Email Header print MAIL “To: $ton”; print MAIL “From: $fromn”; print MAIL “Subject: $subjectnn”; # Email Body print MAIL $message; close(MAIL); print “Email Sent Successfullyn”; Actually, the above script is a client email script, which will draft email and submit to the server running locally on your Linux/Unix machine. This script will not be responsible for sending email to actual destination. So you have to make sure email server is properly configured and running on your machine to send email to the given email ID. Sending an HTML Message If you want to send HTML formatted email using sendmail, then you simply need to add Content-type: text/htmln in the header part of the email as follows − #!/usr/bin/perl $to = ”[email protected]”; $from = ”[email protected]”; $subject = ”Test Email”; $message = ”<h1>This is test email sent by Perl Script</h1>”; open(MAIL, “|/usr/sbin/sendmail -t”); # Email Header print MAIL “To: $ton”; print MAIL “From: $fromn”; print MAIL “Subject: $subjectnn”; print MAIL “Content-type: text/htmln”; # Email Body print MAIL $message; close(MAIL); print “Email Sent Successfullyn”; Using MIME::Lite Module If you are working on windows machine, then you will not have access on sendmail utility. But you have alternate to write your own email client using MIME:Lite perl module. You can download this module from MIME-Lite-3.01.tar.gz and install it on your either machine Windows or Linux/Unix. To install it follow the simple steps − $tar xvfz MIME-Lite-3.01.tar.gz $cd MIME-Lite-3.01 $perl Makefile.PL $make $make install That”s it and you will have MIME::Lite module installed on your machine. Now you are ready to send your email with simple scripts explained below. Sending a Plain Message Now following is a script which will take care of sending email to the given email ID − #!/usr/bin/perl use MIME::Lite; $to = ”[email protected]”; $cc = ”[email protected]”; $from = ”[email protected]”; $subject = ”Test Email”; $message = ”This is test email sent by Perl Script”; $msg = MIME::Lite->new( From => $from, To => $to, Cc => $cc, Subject => $subject, Data => $message ); $msg->send; print “Email Sent Successfullyn”; Sending an HTML Message If you want to send HTML formatted email using sendmail, then you simply need to add Content-type: text/htmln in the header part of the email. Following is the script, which will take care of sending HTML formatted email − #!/usr/bin/perl use MIME::Lite; $to = ”[email protected]”; $cc = ”[email protected]”; $from = ”[email protected]”; $subject = ”Test Email”; $message = ”<h1>This is test email sent by Perl Script</h1>”; $msg = MIME::Lite->new( From => $from, To => $to, Cc => $cc, Subject => $subject, Data => $message ); $msg->attr(“content-type” => “text/html”); $msg->send; print “Email Sent Successfullyn”; Sending an Attachment If you want to send an attachment, then following script serves the purpose − #!/usr/bin/perl use MIME::Lite; $to = ”[email protected]”; $cc = ”[email protected]”; $from = ”[email protected]”; $subject = ”Test Email”; $message = ”This is test email sent by Perl Script”; $msg = MIME::Lite->new( From => $from, To => $to, Cc => $cc, Subject => $subject, Type => ”multipart/mixed” ); # Add your text message. $msg->attach(Type => ”text”, Data => $message ); # Specify your file as attachement. $msg->attach(Type => ”image/gif”, Path => ”/tmp/logo.gif”, Filename => ”logo.gif”, Disposition => ”attachment” ); $msg->send; print “Email Sent Successfullyn”; You can attach as many files as you like in your email using attach() method. Using SMTP Server If your machine is not running an email server then you can use any other email server available at the remote location. But to use any other email server you will need to have an id, its password, URL, etc. Once you have all the required information, you simple need to provide that information in send() method as follows − $msg->send(”smtp”, “smtp.myisp.net”, AuthUser=>”id”, AuthPass=>”password” ); You can contact your email server administrator to have the above used information and if a user id and password is not already available then your administrator can create it in minutes. Print Page Previous Next Advertisements ”;
Perl – Regular Expressions
Perl – Regular Expressions ”; Previous Next A regular expression is a string of characters that defines the pattern or patterns you are viewing. The syntax of regular expressions in Perl is very similar to what you will find within other regular expression.supporting programs, such as sed, grep, and awk. The basic method for applying a regular expression is to use the pattern binding operators =~ and !~. The first operator is a test and assignment operator. There are three regular expression operators within Perl. Match Regular Expression – m// Substitute Regular Expression – s/// Transliterate Regular Expression – tr/// The forward slashes in each case act as delimiters for the regular expression (regex) that you are specifying. If you are comfortable with any other delimiter, then you can use in place of forward slash. 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 matchingn”; } else { print “First time is not matchingn”; } $bar = “foo”; if ($bar =~ /foo/) { print “Second time is matchingn”; } else { print “Second time is not matchingn”; } 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 matchingn”; } else { print “First time is not matchingn”; } $bar = “foo”; if ($bar =~ m{foo}) { print “Second time is matchingn”; } else { print “Second time is not matchingn”; } 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: $lastn”; 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 “$stringn”; 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
Perl – Special Variables
Perl – Special Variables ”; Previous Next There are some variables which have a predefined and special meaning in Perl. They are the variables that use punctuation characters after the usual variable indicator ($, @, or %), such as $_ ( explained below ). Most of the special variables have an english like long name, e.g., Operating System Error variable $! can be written as $OS_ERROR. But if you are going to use english like names, then you would have to put one line use English; at the top of your program file. This guides the interpreter to pickup exact meaning of the variable. The most commonly used special variable is $_, which contains the default input and pattern-searching string. For example, in the following lines − Live Demo #!/usr/bin/perl foreach (”hickory”,”dickory”,”doc”) { print $_; print “n”; } When executed, this will produce the following result − hickory dickory doc Again, let”s check the same example without using $_ variable explicitly − Live Demo #!/usr/bin/perl foreach (”hickory”,”dickory”,”doc”) { print; print “n”; } When executed, this will also produce the following result − hickory dickory doc The first time the loop is executed, “hickory” is printed. The second time around, “dickory” is printed, and the third time, “doc” is printed. That”s because in each iteration of the loop, the current string is placed in $_, and is used by default by print. Here are the places where Perl will assume $_ even if you don”t specify it − Various unary functions, including functions like ord and int, as well as the all file tests (-f, -d) except for -t, which defaults to STDIN. Various list functions like print and unlink. The pattern-matching operations m//, s///, and tr/// when used without an =~ operator. The default iterator variable in a foreach loop if no other variable is supplied. The implicit iterator variable in the grep and map functions. The default place to put an input record when a line-input operation”s result is tested by itself as the sole criterion of a while test (i.e., ). Note that outside of a while test, this will not happen. Special Variable Types Based on the usage and nature of special variables, we can categorize them in the following categories − Global Scalar Special Variables. Global Array Special Variables. Global Hash Special Variables. Global Special Filehandles. Global Special Constants. Regular Expression Special Variables. Filehandle Special Variables. 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 “34”. $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
Perl – Discussion
Discuss Perl ”; Previous Next Perl is a programming language developed by Larry Wall, especially designed for text processing. It stands for Practical Extraction and Report Language. It runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX. This tutorial provides a complete understanding on Perl. Please enable JavaScript to view the comments powered by Disqus. Print Page Previous Next Advertisements ”;
Perl – IF…ELSE
Perl Conditional Statements – IF…ELSE ”; Previous Next Perl conditional statements helps in the decision making, which require that the programmer specifies one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false. Following is the general from of a typical decision making structure found in most of the programming languages − The number 0, the strings ”0” and “” , the empty list () , and undef are all false in a boolean context and all other values are true. Negation of a true value by ! or not returns a special false value. Perl programming language provides the following types of conditional statements. Sr.No. Statement & Description 1 if statement An if statement consists of a boolean expression followed by one or more statements. 2 if…else statement An if statement can be followed by an optional else statement. 3 if…elsif…else statement An if statement can be followed by an optional elsif statement and then by an optional else statement. 4 unless statement An unless statement consists of a boolean expression followed by one or more statements. 5 unless…else statement An unless statement can be followed by an optional else statement. 6 unless…elsif..else statement An unless statement can be followed by an optional elsif statement and then by an optional else statement. 7 switch statement With the latest versions of Perl, you can make use of the switch statement. which allows a simple way of comparing a variable value against various conditions. The ? : 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 − Live Demo #!/usr/local/bin/perl $name = “Ali”; $age = 10; $status = ($age > 60 )? “A senior citizen” : “Not a senior citizen”; print “$name is – $statusn”; This will produce the following result − Ali is – Not a senior citizen Print Page Previous Next Advertisements ”;
Perl – Directories
Perl – Directories ”; Previous Next Following are the standard functions used to play with directories. 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 “$filen”; } 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 successfullyn”; 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 successfullyn”; 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 $dirn”; Print Page Previous Next Advertisements ”;