Perl – Environment ”; Previous Next 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 Perl, you will need ”make”, which is part of the Apples developer tools usually supplied with Mac OS install DVDs. You do not need the latest version of Xcode (which is now charged for) in order to install make. Here are the simple steps to install Perl on Mac OS X machine. Open a Web browser and go to https://www.perl.org/get.html. Follow the link to download zipped source code available for Mac OS X. 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 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. Running Perl The following are the different ways to start Perl. Interactive Interpreter You can enter perl and start coding right away in the interactive interpreter by starting it from the command line. You can do this from Unix, DOS, or any other system, which provides you a command-line interpreter or shell window. $perl -e <perl code> # Unix/Linux or C:>perl -e <perl code> # Windows/DOS Here is the list of all the available command line options − Sr.No. Option & Description 1 -d[:debugger] Runs program under debugger 2 -Idirectory Specifies @INC/#include directory 3 -T Enables tainting checks 4 -t Enables tainting warnings 5 -U Allows unsafe operations 6 -w Enables many useful warnings 7 -W Enables all warnings 8 -X Disables all warnings 9 -e program Runs Perl script sent in as program 10 file Runs Perl script from a given file Script from the Command-line A Perl script is a text file, which keeps perl code in it and it can be executed at the command line by invoking the interpreter on your application, as in the following − $perl script.pl # Unix/Linux or C:>perl script.pl # Windows/DOS Integrated Development Environment You can run Perl from a graphical user interface (GUI) environment as well. All you need is a GUI application on your system that supports Perl. You can download Padre, the Perl IDE. You can also use Eclipse Plugin EPIC – Perl Editor and IDE for Eclipse if you are familiar with Eclipse. Before proceeding to the next chapter, make sure your environment is properly setup and working perfectly fine. If you are not able to setup the environment properly then you can take help from your system admininstrator. All the examples given in subsequent chapters have been executed with v5.16.2 version available on the CentOS flavor of Linux. Print Page Previous Next
Category: perl
Perl – Formats
Perl – Formats ”; Previous Next Perl uses a writing template called a ”format” to output reports. To use the format feature of Perl, you have to define a format first and then you can use that format to write formatted data. Define a Format Following is the syntax to define a Perl format − format FormatName = fieldline value_one, value_two, value_three fieldline value_one, value_two . Here FormatName represents the name of the format. The fieldline is the specific way, the data should be formatted. The values lines represent the values that will be entered into the field line. You end the format with a single period. Next fieldline can contain any text or fieldholders. The fieldholders hold space for data that will be placed there at a later date. A fieldholder has the format − @<<<< This fieldholder is left-justified, with a field space of 5. You must count the @ sign and the < signs to know the number of spaces in the field. Other field holders include − @>>>> right-justified @|||| centered @####.## numeric field holder @* multiline field holder An example format would be − format EMPLOYEE = =================================== @<<<<<<<<<<<<<<<<<<<<<< @<< $name $age @#####.## $salary =================================== . In this example, $name would be written as left justify within 22 character spaces and after that age will be written in two spaces. Using the Format In order to invoke this format declaration, we would use the write keyword − write EMPLOYEE; The problem is that the format name is usually the name of an open file handle, and the write statement will send the output to this file handle. As we want the data sent to the STDOUT, we must associate EMPLOYEE with the STDOUT filehandle. First, however, we must make sure that that STDOUT is our selected file handle, using the select() function. select(STDOUT); We would then associate EMPLOYEE with STDOUT by setting the new format name with STDOUT, using the special variable $~ or $FORMAT_NAME as follows − $~ = “EMPLOYEE”; When we now do a write(), the data would be sent to STDOUT. Remember: if you are going to write your report in any other file handle instead of STDOUT then you can use select() function to select that file handle and rest of the logic will remain the same. Let”s take the following example. Here we have hard coded values just for showing the usage. In actual usage you will read values from a file or database to generate actual reports and you may need to write final report again into a file. Live Demo #!/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; } When executed, this will produce the following result − =================================== Ali 20 2000.00 =================================== =================================== Raza 30 2500.00 =================================== =================================== Jaffer 40 4000.00 =================================== Define a Report Header Everything looks fine. But you would be interested in adding a header to your report. This header will be printed on top of each page. It is very simple to do this. Apart from defining a template you would have to define a header and assign it to $^ or $FORMAT_TOP_NAME variable − Live Demo #!/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; } Now your report will look like − =================================== Name Age =================================== =================================== Ali 20 2000.00 =================================== =================================== Raza 30 2500.00 =================================== =================================== Jaffer 40 4000.00 =================================== Define a Pagination What about if your report is taking more than one page? You have a solution for that, simply use $% or $FORMAT_PAGE_NUMBER vairable along with header as follows − format EMPLOYEE_TOP = =================================== Name Age Page @< $% =================================== . Now your output will look like as follows − =================================== Name Age Page 1 =================================== =================================== Ali 20 2000.00 =================================== =================================== Raza 30 2500.00 =================================== =================================== Jaffer 40 4000.00 =================================== Number of Lines on a Page You can set the number of lines per page using special variable $= ( or $FORMAT_LINES_PER_PAGE ), By default $= will be 60. Define a Report Footer While $^ or $FORMAT_TOP_NAME contains the name of the current header format, there is no corresponding mechanism to automatically do the same thing for a footer. If you have a fixed-size footer, you can get footers by checking variable $- or $FORMAT_LINES_LEFT before each write() and print the footer yourself if necessary using another format defined as follows − format EMPLOYEE_BOTTOM = End of Page @< $% . For a complete set of variables related to formating, please refer to the Perl Special Variables section. Print Page Previous Next Advertisements ”;
Perl – Loops
Perl – Loops ”; Previous Next There may be a situation when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. Programming languages provide various control structures that allow for more complicated execution paths. A loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages − Perl programming language provides the following types of loop to handle the looping requirements. Sr.No. Loop Type & Description 1 while loop Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body. 2 until loop Repeats a statement or group of statements until a given condition becomes true. It tests the condition before executing the loop body. 3 for loop Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable. 4 foreach loop The foreach loop iterates over a normal list value and sets the variable VAR to be each element of the list in turn. 5 do…while loop Like a while statement, except that it tests the condition at the end of the loop body 6 nested loops You can use one or more loop inside any another while, for or do..while loop. Loop Control Statements Loop control statements change the execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. Perl supports the following control statements. Click the following links to check their detail. Sr.No. Control Statement & Description 1 next statement Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating. 2 last statement Terminates the loop statement and transfers execution to the statement immediately following the loop. 3 continue statement A continue BLOCK, it is always executed just before the conditional is about to be evaluated again. 4 redo statement The redo command restarts the loop block without evaluating the conditional again. The continue block, if any, is not executed. 5 goto statement Perl supports a goto command with three forms: goto label, goto expr, and goto &name. The Infinite Loop A loop becomes infinite loop if a condition never becomes false. The for loop is traditionally used for this purpose. Since none of the three expressions that form the for loop are required, you can make an endless loop by leaving the conditional expression empty. #!/usr/local/bin/perl for( ; ; ) { printf “This loop will run forever.n”; } You can terminate the above infinite loop by pressing the Ctrl + C keys. When the conditional expression is absent, it is assumed to be true. You may have an initialization and increment expression, but as a programmer more commonly use the for (;;) construct to signify an infinite loop. Print Page Previous Next Advertisements ”;
Perl – Date & Time
Perl – Date and Time ”; Previous Next This chapter will give you the basic understanding on how to process and manipulate dates and times in Perl. Current Date and Time Let”s start with localtime() function, which returns values for the current date and time if given no arguments. Following is the 9-element list returned by the localtime function while using in list context − sec, # seconds of minutes from 0 to 61 min, # minutes of hour from 0 to 59 hour, # hours of day from 0 to 24 mday, # day of month from 1 to 31 mon, # month of year from 0 to 11 year, # year since 1900 wday, # days since sunday yday, # days since January 1st isdst # hours of daylight savings time Try the following example to print different elements returned by localtime() function − Live Demo #!/usr/local/bin/perl @months = qw( Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec ); @days = qw(Sun Mon Tue Wed Thu Fri Sat Sun); ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(); print “$mday $months[$mon] $days[$wday]n”; When the above code is executed, it produces the following result − 16 Feb Sat If you will use localtime() function in scalar context, then it will return date and time from the current time zone set in the system. Try the following example to print current date and time in full format − Live Demo #!/usr/local/bin/perl $datestring = localtime(); print “Local date and time $datestringn”; When the above code is executed, it produces the following result − Local date and time Sat Feb 16 06:50:45 2013 GMT Time The function gmtime() works just like localtime() function but the returned values are localized for the standard Greenwich time zone. When called in list context, $isdst, the last value returned by gmtime, is always 0. There is no Daylight Saving Time in GMT. You should make a note on the fact that localtime() will return the current local time on the machine that runs the script and gmtime() will return the universal Greenwich Mean Time, or GMT (or UTC). Try the following example to print the current date and time but on GMT scale − Live Demo #!/usr/local/bin/perl $datestring = gmtime(); print “GMT date and time $datestringn”; When the above code is executed, it produces the following result − GMT date and time Sat Feb 16 13:50:45 2013 Format Date and Time You can use localtime() function to get a list of 9-elements and later you can use the printf() function to format date and time based on your requirements as follows − Live Demo #!/usr/local/bin/perl ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(); printf(“Time Format – HH:MM:SSn”); printf(“%02d:%02d:%02d”, $hour, $min, $sec); When the above code is executed, it produces the following result − Time Format – HH:MM:SS 06:58:52 Epoch time You can use the time() function to get epoch time, i.e., the numbers of seconds that have elapsed since a given date, in Unix is January 1, 1970. Live Demo #!/usr/local/bin/perl $epoc = time(); print “Number of seconds since Jan 1, 1970 – $epocn”; When the above code is executed, it produces the following result − Number of seconds since Jan 1, 1970 – 1361022130 You can convert a given number of seconds into date and time string as follows − Live Demo #!/usr/local/bin/perl $datestring = localtime(); print “Current date and time $datestringn”; $epoc = time(); $epoc = $epoc – 24 * 60 * 60; # one day before of current date. $datestring = localtime($epoc); print “Yesterday”s date and time $datestringn”; When the above code is executed, it produces the following result − Current date and time Tue Jun 5 05:54:43 2018 Yesterday”s date and time Mon Jun 4 05:54:43 2018 POSIX Function strftime() You can use the POSIX function strftime() to format date and time with the help of the following table. Please note that the specifiers marked with an asterisk (*) are locale-dependent. Specifier Replaced by Example %a Abbreviated weekday name * Thu %A Full weekday name * Thursday %b Abbreviated month name * Aug %B Full month name * August %c Date and time representation * Thu Aug 23 14:55:02 2001 %C Year divided by 100 and truncated to integer (00-99) 20 %d Day of the month, zero-padded (01-31) 23 %D Short MM/DD/YY date, equivalent to %m/%d/%y 08/23/01 %e Day of the month, space-padded ( 1-31) 23 %F Short YYYY-MM-DD date, equivalent to %Y-%m-%d 2001-08-23 %g Week-based year, last two digits (00-99) 01 %G Week-based year 2001 %h Abbreviated month name * (same as %b) Aug %H Hour in 24h format (00-23) 14 %I Hour in 12h format (01-12) 02 %j Day of the year (001-366) 235 %m Month as a decimal number (01-12) 08 %M Minute (00-59) 55 %n New-line character (”n”) %p AM or PM designation PM %r 12-hour clock time * 02:55:02 pm %R 24-hour HH:MM time, equivalent to %H:%M 14:55 %S Second (00-61) 02 %t Horizontal-tab character (”t”) %T ISO 8601 time format (HH:MM:SS), equivalent to %H:%M:%S 14:55 %u ISO 8601 weekday as number with Monday as 1 (1-7) 4 %U Week number with the first Sunday as the first day of week one (00-53) 33 %V ISO 8601 week number (00-53) 34 %w Weekday as a decimal number with Sunday as 0 (0-6) 4 %W Week number with the first Monday as the first day of week one (00-53) 34 %x Date representation * 08/23/01 %X Time representation * 14:55:02 %y Year, last two digits (00-99) 01 %Y Year 2001 %z ISO 8601 offset from UTC in timezone (1 minute = 1, 1 hour = 100) If timezone cannot be termined, no characters +100 %Z Timezone name or abbreviation * If timezone cannot be termined, no characters CDT %% A % sign % Let”s check the following example to understand the usage − Live Demo #!/usr/local/bin/perl use POSIX qw(strftime); $datestring = strftime “%a %b %e %H:%M:%S %Y”, localtime; printf(“date and time – $datestringn”); # or for GMT formatted appropriately for your
Perl – Embedded Documentation ”; Previous Next You can embed Pod (Plain Old Text) documentation in your Perl modules and scripts. Following is the rule to use embedded documentation in your Perl Code − Start your documentation with an empty line, a =head1 command at the beginning, and end it with a =cut Perl will ignore the Pod text you entered in the code. Following is a simple example of using embedded documentation inside your Perl code − Live Demo #!/usr/bin/perl print “Hello, Worldn”; =head1 Hello, World Example This example demonstrate very basic syntax of Perl. =cut print “Hello, Universen”; When above code is executed, it produces the following result − Hello, World Hello, Universe If you”re going to put your Pod at the end of the file, and you”re using an __END__ or __DATA__ cut mark, make sure to put an empty line there before the first Pod command as follows, otherwise without an empty line before the =head1, many translators wouldn”t have recognized the =head1 as starting a Pod block. Live Demo #!/usr/bin/perl print “Hello, Worldn”; while(<DATA>) { print $_; } __END__ =head1 Hello, World Example This example demonstrate very basic syntax of Perl. print “Hello, Universen”; When above code is executed, it produces the following result − Hello, World =head1 Hello, World Example This example demonstrate very basic syntax of Perl. print “Hello, Universen”; Let”s take one more example for the same code without reading DATA part − Live Demo #!/usr/bin/perl print “Hello, Worldn”; __END__ =head1 Hello, World Example This example demonstrate very basic syntax of Perl. print “Hello, Universen”; When above code is executed, it produces the following result − Hello, World What is POD? Pod is a simple-to-use markup language used for writing documentation for Perl, Perl programs, and Perl modules. There are various translators available for converting Pod to various formats like plain text, HTML, man pages, and more. Pod markup consists of three basic kinds of paragraphs − Ordinary Paragraph − You can use formatting codes in ordinary paragraphs, for bold, italic, code-style , hyperlinks, and more. Verbatim Paragraph − Verbatim paragraphs are usually used for presenting a codeblock or other text which does not require any special parsing or formatting, and which shouldn”t be wrapped. Command Paragraph − A command paragraph is used for special treatment of whole chunks of text, usually as headings or parts of lists. All command paragraphs start with =, followed by an identifier, followed by arbitrary text that the command can use however it pleases. Currently recognized commands are − =pod =head1 Heading Text =head2 Heading Text =head3 Heading Text =head4 Heading Text =over indentlevel =item stuff =back =begin format =end format =for format text… =encoding type =cut POD Examples Consider the following POD − =head1 SYNOPSIS Copyright 2005 [TUTORIALSOPOINT]. =cut You can use pod2html utility available on Linux to convert above POD into HTML, so it will produce following result − Copyright 2005 [TUTORIALSOPOINT]. Next, consider the following example − =head2 An Example List =over 4 =item * This is a bulleted list. =item * Here”s another item. =back =begin html <p> Here”s some embedded HTML. In this block I can include images, apply <span style=”color: green”> styles</span>, or do anything else I can do with HTML. pod parsers that aren”t outputting HTML will completely ignore it. </p> =end html When you convert the above POD into HTML using pod2html, it will produce the following result − An Example List This is a bulleted list. Here”s another item. Here”s some embedded HTML. In this block I can include images, apply styles, or do anything else I can do with HTML. pod parsers that aren”t outputting HTML will completely ignore it. Print Page Previous Next Advertisements ”;
Perl – Error Handling
Perl – Error Handling ”; Previous Next The execution and the errors always go together. If you are opening a file which does not exist. then if you did not handle this situation properly then your program is considered to be of bad quality. The program stops if an error occurs. So a proper error handling is used to handle various type of errors, which may occur during a program execution and take appropriate action instead of halting program completely. You can identify and trap an error in a number of different ways. Its very easy to trap errors in Perl and then handling them properly. Here are few methods which can be used. The if statement The if statement is the obvious choice when you need to check the return value from a statement; for example − if(open(DATA, $file)) { … } else { die “Error: Couldn”t open the file – $!”; } Here variable $! returns the actual error message. Alternatively, we can reduce the statement to one line in situations where it makes sense to do so; for example − open(DATA, $file) || die “Error: Couldn”t open the file $!”; The unless Function The unless function is the logical opposite to if: statements can completely bypass the success status and only be executed if the expression returns false. For example − unless(chdir(“/etc”)) { die “Error: Can”t change directory – $!”; } The unless statement is best used when you want to raise an error or alternative only if the expression fails. The statement also makes sense when used in a single-line statement − die “Error: Can”t change directory!: $!” unless(chdir(“/etc”)); Here we die only if the chdir operation fails, and it reads nicely. The ternary Operator For very short tests, you can use the conditional operator ?: print(exists($hash{value}) ? ”There” : ”Missing”,”n”); It”s not quite so clear here what we are trying to achieve, but the effect is the same as using an if or unless statement. The conditional operator is best used when you want to quickly return one of the two values within an expression or statement. The warn Function The warn function just raises a warning, a message is printed to STDERR, but no further action is taken. So it is more useful if you just want to print a warning for the user and proceed with rest of the operation − chdir(”/etc”) or warn “Can”t change directory”; The die Function The die function works just like warn, except that it also calls exit. Within a normal script, this function has the effect of immediately terminating execution. You should use this function in case it is useless to proceed if there is an error in the program − chdir(”/etc”) or die “Can”t change directory”; Errors within Modules There are two different situations we should be able to handle − Reporting an error in a module that quotes the module”s filename and line number – this is useful when debugging a module, or when you specifically want to raise a module-related, rather than script-related, error. Reporting an error within a module that quotes the caller”s information so that you can debug the line within the script that caused the error. Errors raised in this fashion are useful to the end-user, because they highlight the error in relation to the calling script”s origination line. The warn and die functions work slightly differently than you would expect when called from within a module. For example, the simple module − package T; require Exporter; @ISA = qw/Exporter/; @EXPORT = qw/function/; use Carp; sub function { warn “Error in module!”; } 1; When called from a script like below − use T; function(); It will produce the following result − Error in module! at T.pm line 9. This is more or less what you might expected, but not necessarily what you want. From a module programmer”s perspective, the information is useful because it helps to point to a bug within the module itself. For an end-user, the information provided is fairly useless, and for all but the hardened programmer, it is completely pointless. The solution for such problems is the Carp module, which provides a simplified method for reporting errors within modules that return information about the calling script. The Carp module provides four functions: carp, cluck, croak, and confess. These functions are discussed below. The carp Function The carp function is the basic equivalent of warn and prints the message to STDERR without actually exiting the script and printing the script name. package T; require Exporter; @ISA = qw/Exporter/; @EXPORT = qw/function/; use Carp; sub function { carp “Error in module!”; } 1; When called from a script like below − use T; function(); It will produce the following result − Error in module! at test.pl line 4 The cluck Function The cluck function is a sort of supercharged carp, it follows the same basic principle but also prints a stack trace of all the modules that led to the function being called, including the information on the original script. package T; require Exporter; @ISA = qw/Exporter/; @EXPORT = qw/function/; use Carp qw(cluck); sub function { cluck “Error in module!”; } 1; When called from a script like below − use T; function(); It will produce the following result − Error in module! at T.pm line 9 T::function() called at test.pl line 4 The croak Function The croak function is equivalent to die, except that it reports the caller one level up. Like die, this function also exits the script after reporting the error to STDERR − package T; require Exporter; @ISA = qw/Exporter/; @EXPORT = qw/function/; use Carp; sub function { croak “Error in module!”; } 1; When called from a script like below − use T; function(); It will produce the following result − Error in module! at test.pl line 4 As with carp, the same basic rules apply regarding the including of line and file information according to the warn and
Perl – Introduction
Perl – Introduction ”; Previous Next 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. Print Page Previous Next Advertisements ”;
Perl – Variables
Perl – Variables ”; Previous Next 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 Here 25, “John Paul” and 1445.50 are the values assigned to $age, $name and $salary variables, respectively. Shortly we will see how we can assign values to arrays and hashes. 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 − Live Demo #!/usr/bin/perl $age = 25; # An integer assignment $name = “John Paul”; # A string $salary = 1445.50; # A floating point print “Age = $agen”; print “Name = $namen”; print “Salary = $salaryn”; This will produce the following result − Age = 25 Name = John Paul Salary = 1445.5 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. Here is a simple example of using array variables − Live Demo #!/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”; Here we used escape sign () before the $ sign just to print it. Other Perl will understand it as a variable and will print its value. When executed, this will produce the following result − $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. Here is a simple example of using hash variables − Live Demo #!/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”; This will produce the following result − $data{”John Paul”} = 45 $data{”Lisa”} = 30 $data{”Kumar”} = 40 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 − Live Demo #!/usr/bin/perl @names = (”John Paul”, ”Lisa”, ”Kumar”); @copy = @names; $size = @names; print “Given names are : @copyn”; print “Number of names are : $sizen”; 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 − Sr.No. Context & Description 1 Scalar Assignment to a scalar variable evaluates the right-hand side in a scalar context. 2 List Assignment to an array or a hash evaluates the right-hand side in a list context. 3 Boolean Boolean context is simply any place where an expression is being evaluated to see whether it”s true or false. 4 Void This context not only doesn”t care what the return value is, it doesn”t even want a return value. 5 Interpolative This context only happens inside quotes, or things that work like quotes. Print Page Previous Next Advertisements ”;
Perl – References
Perl – References ”; Previous Next A Perl reference is a scalar data type that holds the location of another value which could be scalar, arrays, or hashes. Because of its scalar nature, a reference can be used anywhere, a scalar can be used. You can construct lists containing references to other lists, which can contain references to hashes, and so on. This is how the nested data structures are built in Perl. 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 − Live Demo #!/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”; When above program is executed, it produces the following result − Value of 10 is : 10 Value of 1 2 3 is : 123 Value of %var is : key220key110 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”; When above program is executed, it produces the following result − Reference type in r : SCALAR Reference type in r : ARRAY Reference type in r : HASH 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 − Live Demo #!/usr/bin/perl my $foo = 100; $foo = $foo; print “Value of foo is : “, $$foo, “n”; When above program is executed, it produces the following result − Value of foo is : REF(0x9aae38) 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 − Live Demo #!/usr/bin/perl # Function definition sub PrintHash { my (%hash) = @_; foreach $item (%hash) { print “Item : $itemn”; } } %hash = (”name” => ”Tom”, ”age” => 19); # Create a reference to above function. $cref = &PrintHash; # Function call using reference. &$cref(%hash); When above program is executed, it produces the following result − Item : name Item : Tom Item : age Item : 19 Print Page Previous Next Advertisements ”;
Perl – Arrays
Perl – Arrays ”; Previous Next 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. Here is a simple example of using the array variables − Live Demo #!/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”; Here we have used the escape sign () before the $ sign just to print it. Other Perl will understand it as a variable and will print its value. When executed, this will produce the following result − $ages[0] = 25 $ages[1] = 30 $ages[2] = 40 $names[0] = John Paul $names[1] = Lisa $names[2] = Kumar In Perl, List and Array terms are often used as if they”re interchangeable. But the list is the data, and the array is the variable. 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 − Live Demo #!/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”; This will produce the following result − Mon Tue Wed Sun Sun Mon Array indices start from zero, so to access the first element you need to give 0 as indices. You can also give a negative index, in which case you select the element from the end, rather than the beginning, of the array. This means the following − 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 − Live Demo #!/usr/bin/perl @var_10 = (1..10); @var_20 = (10..20); @var_abc = (a..z); print “@var_10n”; # Prints number from 1 to 10 print “@var_20n”; # Prints number from 10 to 20 print “@var_abcn”; # 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 − Live Demo #!/usr/bin/perl @array = (1,2,3); $array[50] = 4; $size = @array; $max_index = $#array; print “Size: $sizen”; print “Max Index: $max_indexn”; This will produce the following result − Size: 51 Max Index: 50 There are only four elements in the array that contains information, but the array is 51 elements long, with a highest index of 50. 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 = @coinsn”; # add one element at the end of the array push(@coins, “Penny”); print “2. @coins = @coinsn”; # add one element at the beginning of the array unshift(@coins, “Dollar”); print “3. @coins = @coinsn”; # remove one element from the last of the array. pop(@coins); print “4. @coins = @coinsn”; # remove one element from the beginning of the array. shift(@coins); print “5. @coins = @coinsn”; This will produce the following result − 1. @coins = Quarter Dime Nickel 2. @coins = Quarter Dime Nickel Penny 3. @coins = Dollar Quarter Dime Nickel Penny 4. @coins = Dollar Quarter Dime Nickel 5. @coins = Quarter Dime Nickel 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. Live Demo #!/usr/bin/perl @days = qw/Mon