Parrot – Branches

Parrot – Branches ”; Previous Next Code gets a little boring without flow control; for starters, Parrot knows about branching and labels. The branch op is equivalent to Perl”s goto: branch TERRY JOHN: print “fjordsn” branch END MICHAEL: print ” pining” branch GRAHAM TERRY: print “It”s” branch MICHAEL GRAHAM: print ” for the ” branch JOHN END: end It can also perform simple tests to see whether a register contains a true value: set I1, 12 set I2, 5 mod I3, I2, I2 if I3, REMAIND, DIVISOR REMAIND: print “5 divides 12 with remainder ” print I3 branch DONE DIVISOR: print “5 is an integer divisor of 12” DONE: print “n” end Here”s what that would look like in Perl, for comparison: $i1 = 12; $i2 = 5; $i3 = $i1 % $i2; if ($i3) { print “5 divides 12 with remainder “; print $i3; } else { print “5 is an integer divisor of 12”; } print “n”; exit; Parrot Operator We have the full range of numeric comparators: eq, ne, lt, gt, le and ge. Note that you can”t use these operators on arguments of disparate types; you may even need to add the suffix _i or _n to the op, to tell it what type of argument you are using, although the assembler ought to divine this for you, by the time you read this. Print Page Previous Next Advertisements ”;

Parrot – Overview

Parrot – Overview ”; Previous Next When we feed our program into conventional Perl, it is first compiled into an internal representation, or bytecode; this bytecode is then fed into almost separate subsystem inside Perl to be interpreted. So there are two distinct phases of Perl”s operation: Compilation to bytecode and Interpretation of bytecode. This is not unique to Perl. Other languages following this design include Python, Ruby, Tcl and even Java. We also know that there is a Java Virtual Machine (JVM) which is a platform independent execution environment that converts Java bytecode into machine language and executes it. If you understand this concept then you will understand Parrot. Parrot is a virtual machine designed to efficiently compile and execute bytecode for interpreted languages. Parrot is the target for the final Perl 6 compiler, and is used as a backend for Pugs, as well as variety of other languages like Tcl, Ruby, Python etc. Parrot has been written using most popular language “C”. Print Page Previous Next Advertisements ”;

Parrot – Registers

Parrot – Registers ”; Previous Next The current Perl 5 virtual machine is a stack machine. It communicate values between operations by keeping them on a stack. Operations load values onto the stack, do whatever they need to do and put the result back onto the stack. This is easy to work with, but it is slow. To add two numbers together, you need to perform three stack pushes and two stack pops. Worse, the stack has to grow at runtime, and that means allocating memory just when you don”t want to be allocating it. So Parrot is going to break the established tradition for virtual machines, and use a register architecture, more akin to the architecture of a real hardware CPU. This has another advantage. We can use all the existing literature on how to write compilers and optimizers for register-based CPUs for our software CPU! Parrot has specialist registers for each type: 32 IV registers, 32 NV registers, 32 string registers and 32 PMC registers. In Parrot assembler, these are named I1…I32, N1…N32, S1…S32, P1…P32 respectively. Now let”s look at some assembler. We can set these registers with the set operator: set I1, 10 set N1, 3.1415 set S1, “Hello, Parrot” All Parrot ops have the same format: the name of the operator, the destination register and then the operands. Print Page Previous Next Advertisements ”;

Perl – Embedded Documentation

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 &commat; 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 &commat;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” (&commat;) 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 &commat;ages = (25, 30, 40); &commat;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 &commat;names = (”John Paul”, ”Lisa”, ”Kumar”); &commat;copy = &commat;names; $size = &commat;names; print “Given names are : &commat;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 &commat;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 ”;

Parrot – Home

Parrot Tutorial PDF Version Quick Guide Resources Job Search Discussion Parrot is a virtual machine designed to efficiently compile and execute bytecode for interpreted languages. Parrot is designed for dynamic languages. Parrot is a target of variety of languages like Perl, Tcl, Ruby, Python, etc. In this tutorial, we shall learn using Parrot for Perl compiler. Audience This tutorial is designed for users who wish to learn the basics of Parrot and how it works. It explains how to use Parrot with Perl. Parrot is going to change the way you see PERL! Prerequisites This tutorial expects a basic understanding of compilation and interpretation concepts. User should have knowledge of Perl. 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” (&commat;) 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 &commat;ages = (25, 30, 40); &commat;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 &commat; sign and are populated using either parentheses or the qw operator. For example − &commat;array = (1, 2, ”Hello”); &commat;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 − &commat;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 − &commat;array = (1,2,3); print “Size: “,scalar &commat;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 &commat;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 &commat;ARRAY, LIST Pushes the values of the list onto the end of the array. 2 pop &commat;ARRAY Pops off and returns the last value of the array. 3 shift &commat;ARRAY Shifts the first value of the array off and returns it, shortening the array by 1 and moving everything down. 4 unshift &commat;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. &commat;coins = &commat;coinsn”; # add one element at the end of the array push(&commat;coins, “Penny”); print “2. &commat;coins = &commat;coinsn”; # add one element at the beginning of the array unshift(&commat;coins, “Dollar”); print “3. &commat;coins = &commat;coinsn”; # remove one element from the last of the array. pop(&commat;coins); print “4. &commat;coins = &commat;coinsn”; # remove one element from the beginning of the array. shift(&commat;coins); print “5. &commat;coins = &commat;coinsn”; This will produce the following result − 1. &commat;coins = Quarter Dime Nickel 2. &commat;coins = Quarter Dime Nickel Penny 3. &commat;coins = Dollar Quarter Dime Nickel Penny 4. &commat;coins = Dollar Quarter Dime Nickel 5. &commat;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 &commat;days = qw/Mon