Perl – Useful Resources ”; Previous Next The following resources contain additional information on Perl. Please use them to get more in-depth knowledge on this topic. Useful Video Courses Perl Online Training 47 Lectures 4.5 hours Tutorialspoint More Detail Unix and Linux System Administration Fundamentals Course Most Popular 130 Lectures 23 hours Eduonix Learning Solutions More Detail PERL Programming Complete Course 12 Lectures 1.5 hours Harshit Srivastava More Detail Perl for Beginners: Learn A to Z of Perl Scripting Hands-on 31 Lectures 6 hours TELCOMA Global More Detail Penetration Testing the Right Way 12 Lectures 1 hours Stone River ELearning More Detail Perl Programming for Beginners Course Best Seller 68 Lectures 7 hours Stone River ELearning More Detail Print Page Previous Next Advertisements ”;
Category: Computer Programming
Perl – Syntax Overview
Perl – Syntax Overview ”; Previous Next Perl borrows syntax and concepts from many languages: awk, sed, C, Bourne Shell, Smalltalk, Lisp and even English. However, there are some definite differences between the languages. This chapter is designd to quickly get you up to speed on the syntax that is expected in Perl. A Perl program consists of a sequence of declarations and statements, which run from the top to the bottom. Loops, subroutines, and other control structures allow you to jump around within the code. Every simple statement must end with a semicolon (;). Perl is a free-form language: you can format and indent it however you like. Whitespace serves mostly to separate tokens, unlike languages like Python where it is an important part of the syntax, or Fortran where it is immaterial. First Perl Program Interactive Mode Programming You can use Perl interpreter with -e option at command line, which lets you execute Perl statements from the command line. Let”s try something at $ prompt as follows − $perl -e ”print “Hello Worldn”” This execution will produce the following result − Hello, world Script Mode Programming Assuming you are already on $ prompt, let”s open a text file hello.pl using vi or vim editor and put the following lines inside your file. Live Demo #!/usr/bin/perl # This will print “Hello, World” print “Hello, worldn”; Here /usr/bin/perl is actual the perl interpreter binary. Before you execute your script, be sure to change the mode of the script file and give execution priviledge, generally a setting of 0755 works perfectly and finally you execute the above script as follows − $chmod 0755 hello.pl $./hello.pl This execution will produce the following result − Hello, world You can use parentheses for functions arguments or omit them according to your personal taste. They are only required occasionally to clarify the issues of precedence. Following two statements produce the same result. print(“Hello, worldn”); print “Hello, worldn”; Perl File Extension A Perl script can be created inside of any normal simple-text editor program. There are several programs available for every type of platform. There are many programs designd for programmers available for download on the web. As a Perl convention, a Perl file must be saved with a .pl or .PL file extension in order to be recognized as a functioning Perl script. File names can contain numbers, symbols, and letters but must not contain a space. Use an underscore (_) in places of spaces. Comments in Perl Comments in any programming language are friends of developers. Comments can be used to make program user friendly and they are simply skipped by the interpreter without impacting the code functionality. For example, in the above program, a line starting with hash # is a comment. Simply saying comments in Perl start with a hash symbol and run to the end of the line − # This is a comment in perl Lines starting with = are interpreted as the start of a section of embedded documentation (pod), and all subsequent lines until the next =cut are ignored by the compiler. Following is the example − Live Demo #!/usr/bin/perl # This is a single line comment print “Hello, worldn”; =begin comment This is all part of multiline comment. You can use as many lines as you like These comments will be ignored by the compiler until the next =cut is encountered. =cut This will produce the following result − Hello, world Whitespaces in Perl A Perl program does not care about whitespaces. Following program works perfectly fine − #!/usr/bin/perl print “Hello, worldn”; But if spaces are inside the quoted strings, then they would be printed as is. For example − Live Demo #!/usr/bin/perl # This would print with a line break in the middle print “Hello worldn”; This will produce the following result − Hello world All types of whitespace like spaces, tabs, newlines, etc. are equivalent for the interpreter when they are used outside of the quotes. A line containing only whitespace, possibly with a comment, is known as a blank line, and Perl totally ignores it. Single and Double Quotes in Perl You can use double quotes or single quotes around literal strings as follows − Live Demo #!/usr/bin/perl print “Hello, worldn”; print ”Hello, worldn”; This will produce the following result − Hello, world Hello, worldn$ There is an important difference in single and double quotes. Only double quotes interpolate variables and special characters such as newlines n, whereas single quote does not interpolate any variable or special character. Check below example where we are using $a as a variable to store a value and later printing that value − Live Demo #!/usr/bin/perl $a = 10; print “Value of a = $an”; print ”Value of a = $an”; This will produce the following result − Value of a = 10 Value of a = $an$ “Here” Documents You can store or print multiline text with a great comfort. Even you can make use of variables inside the “here” document. Below is a simple syntax, check carefully there must be no space between the << and the identifier. An identifier may be either a bare word or some quoted text like we used EOF below. If identifier is quoted, the type of quote you use determines the treatment of the text inside the here docoment, just as in regular quoting. An unquoted identifier works like double quotes. Live Demo #!/usr/bin/perl $a = 10; $var = <<“EOF”; This is the syntax for here document and it will continue until it encounters a EOF in the first line. This is case of double quote so variable value will be interpolated. For example value of a = $a EOF print “$varn”; $var = <<”EOF”; This is case of single quote so variable value will be interpolated. For example value of a = $a EOF print “$varn”; This will produce the following result − This is the syntax for here document and it will continue until
Perl – Operators
Perl – Operators ”; Previous Next What is an Operator? Simple answer can be given using the expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and + is called operator. Perl language supports many operator types, but following is a list of important and most frequently used operators − Arithmetic Operators Equality Operators Logical Operators Assignment Operators Bitwise Operators Logical Operators Quote-like Operators Miscellaneous Operators Lets have a look at all the operators one by one. Perl Arithmetic Operators Assume variable $a holds 10 and variable $b holds 20, then following are the Perl arithmatic operators − Show Example Sr.No. Operator & Description 1 + ( Addition ) Adds values on either side of the operator Example − $a + $b will give 30 2 – (Subtraction) Subtracts right hand operand from left hand operand Example − $a – $b will give -10 3 * (Multiplication) Multiplies values on either side of the operator Example − $a * $b will give 200 4 / (Division) Divides left hand operand by right hand operand Example − $b / $a will give 2 5 % (Modulus) Divides left hand operand by right hand operand and returns remainder Example − $b % $a will give 0 6 ** (Exponent) Performs exponential (power) calculation on operators Example − $a**$b will give 10 to the power 20 Perl Equality Operators These are also called relational operators. Assume variable $a holds 10 and variable $b holds 20 then, lets check the following numeric equality operators − Show Example Sr.No. Operator & Description 1 == (equal to) Checks if the value of two operands are equal or not, if yes then condition becomes true. Example − ($a == $b) is not true. 2 != (not equal to) Checks if the value of two operands are equal or not, if values are not equal then condition becomes true. Example − ($a != $b) is true. 3 <=> Checks if the value of two operands are equal or not, and returns -1, 0, or 1 depending on whether the left argument is numerically less than, equal to, or greater than the right argument. Example − ($a <=> $b) returns -1. 4 > (greater than) Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. Example − ($a > $b) is not true. 5 < (less than) Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. Example − ($a < $b) is true. 6 >= (greater than or equal to) Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. Example − ($a >= $b) is not true. 7 <= (less than or equal to) Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. Example − ($a <= $b) is true. Below is a list of equity operators. Assume variable $a holds “abc” and variable $b holds “xyz” then, lets check the following string equality operators − Show Example Sr.No. Operator & Description 1 lt Returns true if the left argument is stringwise less than the right argument. Example − ($a lt $b) is true. 2 gt Returns true if the left argument is stringwise greater than the right argument. Example − ($a gt $b) is false. 3 le Returns true if the left argument is stringwise less than or equal to the right argument. Example − ($a le $b) is true. 4 ge Returns true if the left argument is stringwise greater than or equal to the right argument. Example − ($a ge $b) is false. 5 eq Returns true if the left argument is stringwise equal to the right argument. Example − ($a eq $b) is false. 6 ne Returns true if the left argument is stringwise not equal to the right argument. Example − ($a ne $b) is true. 7 cmp Returns -1, 0, or 1 depending on whether the left argument is stringwise less than, equal to, or greater than the right argument. Example − ($a cmp $b) is -1. Perl Assignment Operators Assume variable $a holds 10 and variable $b holds 20, then below are the assignment operators available in Perl and their usage − Show Example Sr.No. Operator & Description 1 = Simple assignment operator, Assigns values from right side operands to left side operand Example − $c = $a + $b will assigned value of $a + $b into $c 2 += Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand Example − $c += $a is equivalent to $c = $c + $a 3 -= Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand Example − $c -= $a is equivalent to $c = $c – $a 4 *= Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand Example − $c *= $a is equivalent to $c = $c * $a 5 /= Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand Example − $c /= $a is equivalent to $c = $c / $a 6 %= Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand Example − $c %= $a is equivalent to $c = $c % a 7 **= Exponent AND assignment operator, Performs exponential (power) calculation on operators and assign value to the left operand Example − $c **= $a is equivalent to $c = $c ** $a Perl Bitwise Operators Bitwise operator works on bits and perform bit by bit operation. Assume if $a = 60; and
Perl – Coding Standard
Perl – Coding Standard ”; Previous Next Each programmer will, of course, have his or her own preferences in regards to formatting, but there are some general guidelines that will make your programs easier to read, understand, and maintain. The most important thing is to run your programs under the -w flag at all times. You may turn it off explicitly for particular portions of code via the no warnings pragma or the $^W variable if you must. You should also always run under use strict or know the reason why not. The use sigtrap and even use diagnostics pragmas may also prove useful. Regarding aesthetics of code lay out, about the only thing Larry cares strongly about is that the closing curly bracket of a multi-line BLOCK should line up with the keyword that started the construct. Beyond that, he has other preferences that aren”t so strong − 4-column indent. Opening curly on same line as keyword, if possible, otherwise line up. Space before the opening curly of a multi-line BLOCK. One-line BLOCK may be put on one line, including curlies. No space before the semicolon. Semicolon omitted in “short” one-line BLOCK. Space around most operators. Space around a “complex” subscript (inside brackets). Blank lines between chunks that do different things. Uncuddled elses. No space between function name and its opening parenthesis. Space after each comma. Long lines broken after an operator (except and and or). Space after last parenthesis matching on current line. Line up corresponding items vertically. Omit redundant punctuation as long as clarity doesn”t suffer. Here are some other more substantive style issues to think about: Just because you CAN do something a particular way doesn”t mean that you SHOULD do it that way. Perl is designed to give you several ways to do anything, so consider picking the most readable one. For instance − open(FOO,$foo) || die “Can”t open $foo: $!”; Is better than − die “Can”t open $foo: $!” unless open(FOO,$foo); Because the second way hides the main point of the statement in a modifier. On the other hand, print “Starting analysisn” if $verbose; Is better than − $verbose && print “Starting analysisn”; Because the main point isn”t whether the user typed -v or not. Don”t go through silly contortions to exit a loop at the top or the bottom, when Perl provides the last operator so you can exit in the middle. Just “outdent” it a little to make it more visible − LINE: for (;;) { statements; last LINE if $foo; next LINE if /^#/; statements; } Let”s see few more important points − Don”t be afraid to use loop labels–they”re there to enhance readability as well as to allow multilevel loop breaks. See the previous example. Avoid using grep() (or map()) or `backticks` in a void context, that is, when you just throw away their return values. Those functions all have return values, so use them. Otherwise use a foreach() loop or the system() function instead. For portability, when using features that may not be implemented on every machine, test the construct in an eval to see if it fails. If you know what version or patchlevel a particular feature was implemented, you can test $] ($PERL_VERSION in English) to see if it will be there. The Config module will also let you interrogate values determined by the Configure program when Perl was installed. Choose mnemonic identifiers. If you can”t remember what mnemonic means, you”ve got a problem. While short identifiers like $gotit are probably ok, use underscores to separate words in longer identifiers. It is generally easier to read $var_names_like_this than $VarNamesLikeThis, especially for non-native speakers of English. It”s also a simple rule that works consistently with VAR_NAMES_LIKE_THIS. Package names are sometimes an exception to this rule. Perl informally reserves lowercase module names for “pragma” modules like integer and strict. Other modules should begin with a capital letter and use mixed case, but probably without underscores due to limitations in primitive file systems” representations of module names as files that must fit into a few sparse bytes. If you have a really hairy regular expression, use the /x modifier and put in some whitespace to make it look a little less like line noise. Don”t use slash as a delimiter when your regexp has slashes or backslashes. Always check the return codes of system calls. Good error messages should go to STDERR, include which program caused the problem, what the failed system call and arguments were, and (VERY IMPORTANT) should contain the standard system error message for what went wrong. Here”s a simple but sufficient example − opendir(D, $dir) or die “can”t opendir $dir: $!”; Think about reusability. Why waste brainpower on a one-shot when you might want to do something like it again? Consider generalizing your code. Consider writing a module or object class. Consider making your code run cleanly with use strict and use warnings (or -w) in effect. Consider giving away your code. Consider changing your whole world view. Consider… oh, never mind. Be consistent. Be nice. Print Page Previous Next Advertisements ”;
Perl – Home
Perl Tutorial PDF Version Quick Guide Resources Job Search Discussion 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. Why to Learn 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. Hello World using Perl. Just to give you a little excitement about Perl, I”m going to give you a small conventional Perl Hello World program, You can try it using Demo link. Live Demo #!/usr/bin/perl # This will print “Hello, World” print “Hello, worldn”; Applications of Perl As mentioned before, Perl is one of the most widely used language over the web. I”m going to list few of them here: 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. Audience This Perl tutorial has been prepared for beginners to help them understand the basic to advanced concepts related to Perl Scripting languages. Prerequisites Before you start practicing with various types of examples given in this reference, we are making an assumption that you have prior exposure to C programming and Unix Shell. Print Page Previous Next Advertisements ”;
Perl – Hashes
Perl – Hashes ”; Previous Next A hash is a set of key/value pairs. Hash variables are preceded by a percent (%) sign. To refer to a single element of a hash, you will use the hash variable name preceded by a “$” sign and followed by the “key” associated with the value in curly brackets.. Here is a simple example of using the 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 Creating Hashes Hashes are created in one of the two following ways. In the first method, you assign a value to a named key on a one-by-one basis − $data{”John Paul”} = 45; $data{”Lisa”} = 30; $data{”Kumar”} = 40; In the second case, you use a list, which is converted by taking individual pairs from the list: the first element of the pair is used as the key, and the second, as the value. For example − %data = (”John Paul”, 45, ”Lisa”, 30, ”Kumar”, 40); For clarity, you can use => as an alias for , to indicate the key/value pairs as follows − %data = (”John Paul” => 45, ”Lisa” => 30, ”Kumar” => 40); Here is one more variant of the above form, have a look at it, here all the keys have been preceded by hyphen (-) and no quotation is required around them − %data = (-JohnPaul => 45, -Lisa => 30, -Kumar => 40); But it is important to note that there is a single word, i.e., without spaces keys have been used in this form of hash formation and if you build-up your hash this way then keys will be accessed using hyphen only as shown below. $val = %data{-JohnPaul} $val = %data{-Lisa} Accessing Hash Elements When accessing individual elements from a hash, you must prefix the variable with a dollar sign ($) and then append the element key within curly brackets after the name of the variable. For example − Live Demo #!/usr/bin/perl %data = (”John Paul” => 45, ”Lisa” => 30, ”Kumar” => 40); print “$data{”John Paul”}n”; print “$data{”Lisa”}n”; print “$data{”Kumar”}n”; This will produce the following result − 45 30 40 Extracting Slices You can extract slices of a hash just as you can extract slices from an array. You will need to use @ prefix for the variable to store the returned value because they will be a list of values − Live Demo #!/uer/bin/perl %data = (-JohnPaul => 45, -Lisa => 30, -Kumar => 40); @array = @data{-JohnPaul, -Lisa}; print “Array : @arrayn”; This will produce the following result − Array : 45 30 Extracting Keys and Values You can get a list of all of the keys from a hash by using keys function, which has the following syntax − keys %HASH This function returns an array of all the keys of the named hash. Following is the example − Live Demo #!/usr/bin/perl %data = (”John Paul” => 45, ”Lisa” => 30, ”Kumar” => 40); @names = keys %data; print “$names[0]n”; print “$names[1]n”; print “$names[2]n”; This will produce the following result − Lisa John Paul Kumar Similarly, you can use values function to get a list of all the values. This function has the following syntax − values %HASH This function returns a normal array consisting of all the values of the named hash. Following is the example − Live Demo #!/usr/bin/perl %data = (”John Paul” => 45, ”Lisa” => 30, ”Kumar” => 40); @ages = values %data; print “$ages[0]n”; print “$ages[1]n”; print “$ages[2]n”; This will produce the following result − 30 45 40 Checking for Existence If you try to access a key/value pair from a hash that doesn”t exist, you”ll normally get the undefined value, and if you have warnings switched on, then you”ll get a warning generated at run time. You can get around this by using the exists function, which returns true if the named key exists, irrespective of what its value might be − Live Demo #!/usr/bin/perl %data = (”John Paul” => 45, ”Lisa” => 30, ”Kumar” => 40); if( exists($data{”Lisa”} ) ) { print “Lisa is $data{”Lisa”} years oldn”; } else { print “I don”t know age of Lisan”; } Here we have introduced the IF…ELSE statement, which we will study in a separate chapter. For now you just assume that if( condition ) part will be executed only when the given condition is true otherwise else part will be executed. So when we execute the above program, it produces the following result because here the given condition exists($data{”Lisa”} returns true − Lisa is 30 years old Getting Hash Size You can get the size – that is, the number of elements from a hash by using the scalar context on either keys or values. Simply saying first you have to get an array of either the keys or values and then you can get the size of array as follows − Live Demo #!/usr/bin/perl %data = (”John Paul” => 45, ”Lisa” => 30, ”Kumar” => 40); @keys = keys %data; $size = @keys; print “1 – Hash size: is $sizen”; @values = values %data; $size = @values; print “2 – Hash size: is $sizen”; This will produce the following result − 1 – Hash size: is 3 2 – Hash size: is 3 Add and Remove Elements in Hashes Adding a new key/value pair can be done with one line of code using simple assignment operator. But to remove an element from the hash you need to use delete function as shown below in the example − Live Demo #!/usr/bin/perl %data = (”John Paul” => 45, ”Lisa” => 30, ”Kumar” => 40); @keys = keys %data; $size = @keys; print “1 – Hash size: is $sizen”; # adding an element to the hash; $data{”Ali”} = 55; @keys
Perl – Subroutines
Perl – Subroutines ”; Previous Next A Perl subroutine or function is a group of statements that together performs a task. You can divide up your code into separate subroutines. How you divide up your code among different subroutines is up to you, but logically the division usually is so each function performs a specific task. Perl uses the terms subroutine, method and function interchangeably. Define and Call a Subroutine The general form of a subroutine definition in Perl programming language is as follows − sub subroutine_name { body of the subroutine } The typical way of calling that Perl subroutine is as follows − subroutine_name( list of arguments ); In versions of Perl before 5.0, the syntax for calling subroutines was slightly different as shown below. This still works in the newest versions of Perl, but it is not recommended since it bypasses the subroutine prototypes. &subroutine_name( list of arguments ); Let”s have a look into the following example, which defines a simple function and then call it. Because Perl compiles your program before executing it, it doesn”t matter where you declare your subroutine. Live Demo #!/usr/bin/perl # Function definition sub Hello { print “Hello, World!n”; } # Function call Hello(); When above program is executed, it produces the following result − Hello, World! Passing Arguments to a Subroutine You can pass various arguments to a subroutine like you do in any other programming language and they can be acessed inside the function using the special array @_. Thus the first argument to the function is in $_[0], the second is in $_[1], and so on. You can pass arrays and hashes as arguments like any scalar but passing more than one array or hash normally causes them to lose their separate identities. So we will use references ( explained in the next chapter ) to pass any array or hash. Let”s try the following example, which takes a list of numbers and then prints their average − Live Demo #!/usr/bin/perl # Function definition sub Average { # get total number of arguments passed. $n = scalar(@_); $sum = 0; foreach $item (@_) { $sum += $item; } $average = $sum / $n; print “Average for the given numbers : $averagen”; } # Function call Average(10, 20, 30); When above program is executed, it produces the following result − Average for the given numbers : 20 Passing Lists to Subroutines Because the @_ variable is an array, it can be used to supply lists to a subroutine. However, because of the way in which Perl accepts and parses lists and arrays, it can be difficult to extract the individual elements from @_. If you have to pass a list along with other scalar arguments, then make list as the last argument as shown below − Live Demo #!/usr/bin/perl # Function definition sub PrintList { my @list = @_; print “Given list is @listn”; } $a = 10; @b = (1, 2, 3, 4); # Function call with list parameter PrintList($a, @b); When above program is executed, it produces the following result − Given list is 10 1 2 3 4 Passing Hashes to Subroutines When you supply a hash to a subroutine or operator that accepts a list, then hash is automatically translated into a list of key/value pairs. For example − Live Demo #!/usr/bin/perl # Function definition sub PrintHash { my (%hash) = @_; foreach my $key ( keys %hash ) { my $value = $hash{$key}; print “$key : $valuen”; } } %hash = (”name” => ”Tom”, ”age” => 19); # Function call with hash parameter PrintHash(%hash); When above program is executed, it produces the following result − name : Tom age : 19 Returning Value from a Subroutine You can return a value from subroutine like you do in any other programming language. If you are not returning a value from a subroutine then whatever calculation is last performed in a subroutine is automatically also the return value. You can return arrays and hashes from the subroutine like any scalar but returning more than one array or hash normally causes them to lose their separate identities. So we will use references ( explained in the next chapter ) to return any array or hash from a function. Let”s try the following example, which takes a list of numbers and then returns their average − Live Demo #!/usr/bin/perl # Function definition sub Average { # get total number of arguments passed. $n = scalar(@_); $sum = 0; foreach $item (@_) { $sum += $item; } $average = $sum / $n; return $average; } # Function call $num = Average(10, 20, 30); print “Average for the given numbers : $numn”; When above program is executed, it produces the following result − Average for the given numbers : 20 Private Variables in a Subroutine By default, all variables in Perl are global variables, which means they can be accessed from anywhere in the program. But you can create private variables called lexical variables at any time with the my operator. The my operator confines a variable to a particular region of code in which it can be used and accessed. Outside that region, this variable cannot be used or accessed. This region is called its scope. A lexical scope is usually a block of code with a set of braces around it, such as those defining the body of the subroutine or those marking the code blocks of if, while, for, foreach, and eval statements. Following is an example showing you how to define a single or multiple private variables using my operator − sub somefunc { my $variable; # $variable is invisible outside somefunc() my ($another, @an_array, %a_hash); # declaring many variables at once } Let”s check the following example to distinguish between global and private variables − Live Demo #!/usr/bin/perl # Global variable $string = “Hello, World!”; # Function definition sub PrintHello { # Private variable for PrintHello function my $string; $string = “Hello,
Perl – Packages & Modules
Perl – Packages and Modules ”; Previous Next What are Packages? The package statement switches the current naming context to a specified namespace (symbol table). Thus − A package is a collection of code which lives in its own namespace. A namespace is a named collection of unique variable names (also called a symbol table). Namespaces prevent variable name collisions between packages. Packages enable the construction of modules which, when used, won”t clobber variables and functions outside of the modules”s own namespace. The package stays in effect until either another package statement is invoked, or until the end of the current block or file. You can explicitly refer to variables within a package using the :: package qualifier. Following is an example having main and Foo packages in a file. Here special variable __PACKAGE__ has been used to print the package name. Live Demo #!/usr/bin/perl # This is main package $i = 1; print “Package name : ” , __PACKAGE__ , ” $in”; package Foo; # This is Foo package $i = 10; print “Package name : ” , __PACKAGE__ , ” $in”; package main; # This is again main package $i = 100; print “Package name : ” , __PACKAGE__ , ” $in”; print “Package name : ” , __PACKAGE__ , ” $Foo::in”; 1; When above code is executed, it produces the following result − Package name : main 1 Package name : Foo 10 Package name : main 100 Package name : main 10 BEGIN and END Blocks You may define any number of code blocks named BEGIN and END, which act as constructors and destructors respectively. BEGIN { … } END { … } BEGIN { … } END { … } Every BEGIN block is executed after the perl script is loaded and compiled but before any other statement is executed. Every END block is executed just before the perl interpreter exits. The BEGIN and END blocks are particularly useful when creating Perl modules. Following example shows its usage − Live Demo #!/usr/bin/perl package Foo; print “Begin and Block Demon”; BEGIN { print “This is BEGIN Blockn” } END { print “This is END Blockn” } 1; When above code is executed, it produces the following result − This is BEGIN Block Begin and Block Demo This is END Block What are Perl Modules? A Perl module is a reusable package defined in a library file whose name is the same as the name of the package with a .pm as extension. A Perl module file called Foo.pm might contain statements like this. #!/usr/bin/perl package Foo; sub bar { print “Hello $_[0]n” } sub blat { print “World $_[0]n” } 1; Few important points about Perl modules The functions require and use will load a module. Both use the list of search paths in @INC to find the module. Both functions require and use call the eval function to process the code. The 1; at the bottom causes eval to evaluate to TRUE (and thus not fail). The Require Function A module can be loaded by calling the require function as follows − #!/usr/bin/perl require Foo; Foo::bar( “a” ); Foo::blat( “b” ); You must have noticed that the subroutine names must be fully qualified to call them. It would be nice to enable the subroutine bar and blat to be imported into our own namespace so we wouldn”t have to use the Foo:: qualifier. The Use Function A module can be loaded by calling the use function. #!/usr/bin/perl use Foo; bar( “a” ); blat( “b” ); Notice that we didn”t have to fully qualify the package”s function names. The use function will export a list of symbols from a module given a few added statements inside a module. require Exporter; @ISA = qw(Exporter); Then, provide a list of symbols (scalars, lists, hashes, subroutines, etc) by filling the list variable named @EXPORT: For Example − package Module; require Exporter; @ISA = qw(Exporter); @EXPORT = qw(bar blat); sub bar { print “Hello $_[0]n” } sub blat { print “World $_[0]n” } sub splat { print “Not $_[0]n” } # Not exported! 1; Create the Perl Module Tree When you are ready to ship your Perl module, then there is standard way of creating a Perl Module Tree. This is done using h2xs utility. This utility comes along with Perl. Here is the syntax to use h2xs − $h2xs -AX -n ModuleName For example, if your module is available in Person.pm file, then simply issue the following command − $h2xs -AX -n Person This will produce the following result − Writing Person/lib/Person.pm Writing Person/Makefile.PL Writing Person/README Writing Person/t/Person.t Writing Person/Changes Writing Person/MANIFEST Here is the descritpion of these options − -A omits the Autoloader code (best used by modules that define a large number of infrequently used subroutines). -X omits XS elements (eXternal Subroutine, where eXternal means external to Perl, i.e., C). -n specifies the name of the module. So above command creates the following structure inside Person directory. Actual result is shown above. Changes Makefile.PL MANIFEST (contains the list of all files in the package) README t/ (test files) lib/ ( Actual source code goes here So finally, you tar this directory structure into a file Person.tar.gz and you can ship it. You will have to update README file with the proper instructions. You can also provide some test examples files in t directory. Installing Perl Module Download a Perl module in the form tar.gz file. Use the following sequence to install any Perl Module Person.pm which has been downloaded in as Person.tar.gz file. tar xvfz Person.tar.gz cd Person perl Makefile.PL make make install The Perl interpreter has a list of directories in which it searches for modules (global array @INC). Print Page Previous Next Advertisements ”;
Parrot – Useful Resources
Parrot – Useful Resources ”; Previous Next The following resources contain additional information on Parrot. Please use them to get more in-depth knowledge on this topic. Useful Links on Parrot Parrot official websites This site is maintaining updated information related to Parrot. Source Code Packages & Source Code for Parrot Tracking Tools Parrot Testing Status Tools Document our testing coverage Parrot Issue Tracker The Parrot Bugtracking System Parrot Issue Tracker: Summary Report Breakdown of tickets by age, platform, etc. Open Patches Patches to get applied Glossary A glossary of important parrot terms Patch & Bug Report Submission Information A brief on patch submission Useful Books on Parrot To enlist your site on this page, please drop an email to [email protected] Print Page Previous Next Advertisements ”;
Parrot – Garbage Collection
Parrot – Garbage Collection ”; Previous Next Like Java Virtual Machine, Parrot also keep you free from worrying about memory de-allocation. Parrot provides garbage collection. Parrot programs do not need to free memory explicitly. Allocated memory will be freed when it is no longer in use i.e. no longer referenced. Parrot Garbage Collector runs periodically to take care of unwanted memory. Print Page Previous Next Advertisements ”;