S. L Unit - 3
S. L Unit - 3
UNIT-III
    Origin of scripting:
             The use of the word 'script' in a computing context dates back to the early 1970s, when
    the originators of the UNIX operating system create the term 'shell script for sequence of
    commands that were to be read from a file and follow in sequence as if they had been typed in
    at the keyword. e.g. an 'AWKscript', a 'perl script' etc., the name 'script' being used for a text
    file that was intended to be executed directly rather than being compiled to a different form of
    file prior to execution.
           Other early occurrences of the term 'script' can be found. For example, in a DOS-based
    system, use of a dial-up connection to a remote system required a communication package that
    used proprietary language to write scripts to automate the sequence of operations required to
    establish a connection to a remote system.
            Note that if we regard a scripts as a sequence of commands to control an application or
    device, a configuration file such as a UNIX 'make file' could be regard as a script.
     However, scripts only becomes interesting when they have the added values that comes from
    using programming concepts such as loops and branches.
    Scripting today:
    SCRIPTING IS USED WITH 3 DIFFRENT MEANINGS:
    1. A new style of programming which allows applications to be developed much faster than
    traditional methods allow, and maks it possible for applications to evolve rapidly to meet
    changing user requirements. This style of programming frequently uses a scripting language to
    interconnect off the shelf components that are themselves written in conventional language.
    Applications built in this way are called 'glue applications and the language is called a 'glue
    language'.
2. Using a scripting language to manipulate, customize and automate the facilities of an existing
    system' as the ECMAScript definition puts it. Here the script is used to control an application
    that privides a programmable interface: this may be an API, though more commonly the
    application is construted from a collection of objects whose properties and methods are exposed
    to the scripting language. Example: use of Visual Basic for applications to control the
    applications in the Microsoft Office Suite..
    3. Using a scripting language with its rich funcationaliy and case of use as an alternate to a
    conventional language for general programming tasks particularly system programming and
    administration. Examples: are UNIX system. adminstrators have for a long time used scripting
    languages for system maintenace tasks, and administrators of WINDOWS NT systems are
    adopting a scripting language PERL for their work.
          Integrated compile and run: SL's are usually characterized as interpreted languages,
           but this is just an oversimplification. They operate on an immediate execution, without
           need to issue separate command to compile the program and then to run the resulting
           object file, and without the need to link extensive libraries into he object code. This is
           done automatically. A few SL'S are indeed implemented as strict interpreters.
          Low overheads and ease of use:
           1. Variables can be declared by use
           2. The number of different data types is usually limited
           3. Everything is string by context it will be converted as number(vice versa) 4.number
           of data structures is limited(arrays)
          Enhanced functionality: SL's usually have enhanced functionality in some. areas. For
           example most languages provide string manipulation based on the use of regular
           expressions, while other languages provide easy access to low- level operating system
           facilities, or to the API, or object exported by an application.
          Efficiency is not an issue: Ease of use is achieved at the expense of efficiency, because
           efficiency is not an issue in the applications for which
          A scripting language is usually interpreted from source code or bytecode. By contrast,
           the software environment the scripts are written for is typically written in a compiled
           language and distributed in machine code form.
          Scripting languages may be designed for use by end users of a program - end- user
           development or may be only for internal use by developers, so they can write portions
           of the program in the scripting language.
          Scripting languages typically use abstraction, a form of information hiding. to spare
           users the details of internal variable types, data storage, and memory management.
          Scripts are often created or modified by the person executing them, but they are also
           often distributed, such as when large portions of games are written. in a scripting
           language.
    One of the prime examples of these languages is Microsoft-created Visual Basic language, and
    especially it's subset named Visual Basic for Applications, designed explicitly for office
    applications programming
    3. Markup languages are a special case in the sense that they are not a real programming
    languages, but rather a set of special command words called 'tags' used to mark up parts of text
    documents, that are later used by special programs called processors, to do all kinds of
    transformations to the text, such as displaying it in a browser, or converting it to some other
    data format. The basic idea of markup. languages is the separation of contents and structure,
    and also including formatting commands and interactive objects into the documents. The first
    markup language named GML (Generic Markup Language) was created in 1969
    1. Command scripting languages are the oldest class of scripting languages. They appeared in
    1960, when a need for programs and tasks control arised. The most known language from the
    first generation of such languages is JCL (Job Control Language), created for IBM OS/360
    operating system. Modern examples of such languages include shell language, described
    above, and also text-processing languages, such as sed and awk. These languages were one of
    the first to directly include support for regular expression matching a feature that later was
    included into more general-purpose languages, such as Perl..
        Implementations exist for the Java Virtual Machine and also for Microsoft Intermediate
         Language used on Microsoft .NET platform.
        Unlike Perl and Python, which make it easy to write completely standalone programs,
         Tel relies heavily on C and C++ extension modules.
    Web scripting:
    Web is the most fertile areas for the application of scripting languages.
    Web scripting divides into three areas
       1. processing forms
       2. creating pages with enhanced visual effects and user interaction and
       3. Generating pages 'on the fly' from material held in database.
    Processing Web forms:
        In the original implementation of the web, when the form is submitted for processing,
         the information entered by the user is encoded and sent to the server for processing by
         a CGI script that generates an HTML page to be sent back to the Web browser.
        This processing requires string manipulation to construct the HTML page that
         constitutes the replay, and may also require system access, to run other processes and
         to establish network connections. Perl is also a language that uses CGI scripting.
        Alternatively for processing the form with script running on the server it possible to do
         someclient-side processing within the browser to validate form data before sending it
         to the server by using JavaScript, VBScript etc.
    Dynamic Web pages:
    'Dynamic HTML' makes every component of a Web page (headings, anchors, tables etc.) a
    scriptable object. This makes it possible to provide simple interaction with the user using scripts
    written in JavaScript/Jscript or VBScript, which are interpreted by the browser.
    Microsoft's ActiveX technology allows the creation of pages with more claborate user
    interaction by using embedded visual objects called ActiveX controls. These controls are
    scriptable objects, and can in fact be scripted in a variety languages. This can be scripted by
    using Perl scripting engine.
    Dynamically generated HTML:
    Another form of dynamic Web page is one in which some or all of the HTML is generated by
    scripts executed on the server. A common application of the technique is to construct pages
    whose content is retrieved from a database. For example, Microsoft's IIS web server
    implements Active Server Pages (ASP), which incorporate scripts in Jscript or VBScript.
          The world of VBA for scripting compound documents the world of client-side and
           server-side Web scripting.
    The overlap is complex, for example web scripting can be done in VBScript, JavaScript/Jscrint.
    Perl or TCL. This universe has been enlarged as Perl and The Microsoft world of Visual Basic
    and Active controls The world of VBA for scripting compound documents the world of client-
    side and server-side Web scripting.
    The overlap is complex, for example web scripting can be done in VBScript,
    JavaScript/Jscript, Perl or Tcl. This universe has been enlarged as Perl and Tel are used to
    implement complex applications for large organizations e.g Tcl has been used to develop a
    major banking system, and Perl has been used to implement an enterprise- wide document
    management system for a leading aerospace company.
           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 - Sperl –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
    Script Mode Programming
    Assuming you are already on S prompt, let's open a text file hello.pl using vi or vim editor and
    put the following lines inside your file.
            #!/usr/bin/perl
            #This will print "Hello, World"
            print "Hello, world\n";
    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--
    : perl 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, world\n");
    print "Hello, world\n";
    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
    -
    #!/usr/bin/perl
    #This is a single line comment
    print "Hello, world\n";
    =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, world\n":
    But if spaces are inside the quoted strings, then they would be printed as is. For
    example -
    #!/usr/bin/perl
    #This would print with a line break in the middle
    print "Hello world\n";
    This will produce the following result-
    Hello
    #This would print with a line break in the middle
     print "Hello
     world\n";
     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 -
     #!/usr/bin/perl
     print "Hello, world\n";
     print 'Hello, world\n';
     This will produce the following result -
     Hello, world
     Hello, world\n$
     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 Sa as a variable to
     store a value and later printing that value
     #!/usr/bin/perl
     $a = 10;
     print "Value of a = Sa\n";
     print 'Value of a = Sa\n';
     This will produce the following result -
     Value of a 10
     Value of a Sain$
     "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.
     #!/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 FOF
     print "$var\n";
     $var = <<EOF': This is case of single quote so variable value will be interpolated. For example
     value of a = $a FOF print "$var'n":
     This will produce the following result -
              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 = 10.
              This is case of single quote so variable value will be interpolated. For example value of
               a = Sa
     Escaping Characters
     Perl uses the backslash (1) character to escape any type of character that might interfere with
     our code. Let's take one example where we want to print double quote and S sign -
     #!/usr/bin/perl
     $result = "This is \"number""; print "$result\n";
     print "\Sresult\n":
     This will produce the following result -
     This is "number"
     $result
     Perl Identifiers
          A Perl identifier is a name used to identify a variable, function, class, module, or other
           object. A Perl variable name starts with either S. @ or % followed by zero or more
           letters, underscores, and digits (0 to 9).
          Perl does not allow punctuation characters such as @, $, and within identifiers. Perl is
           a case sensitive programming language. Thus $Manpower and $manpower are two
           different identifiers in Perl.
          Perl is a loosely typed language and there is no need to specify a type for your data
           while using in your program. The Perl interpreter will choose the type based on the
           context of the data itself.
          Perl has three basic data types: scalars, arrays of scalars, and hashes of scalars. also
           known as associative arrays. Here is a little detail about these data types.
                   1       Scalar
                           Scalars are simple variables. They are preceded by a dollar sign (S). A
                           scalar is a number, a string, or a reference. A reference is actually an
                           address of a variable, which we will see in the upcoming chapters.
                   2       Arrays
                           Arrays are ordered lists of scalars that you access with a numeric index.
                           which starts with 0. They are preceded by an "at" sign (@).
                   3       Hashes
                           Hashes are unordered sets of key/value pairs that you access using the
                           keys as subscripts. They are preceded by a percent sign (%).
     Numeric Literals:
     Perl stores all the numbers internally as either signed integers or double- precision floating-
     point values. Numeric literals are specified in any of the following floating-point or integer
     formats-
      Type                                             Value
      Integer                                          1234
      Negative Integer                                 -100
      Floating point                                   2000
      Scientific                                       16.12E14
      Hexadecimal                                      Oxffff
      Octal                                            0577
     String Literals
     Strings are sequences of characters. They are usually alphanumeric values. delimited by either
     single (') or double (") quotes. They work much like UNIX shell quotes where you can use
     single quoted strings and double quoted strings.
     Double-quoted string literals allow variable interpolation, and single-quoted strings are not.
     There are certain characters when they are proceeded by a back slash, have special meaning
     and they are used to represent like newline (\n) or tab (\t).
     You can embed newlines or any of the following Escape sequences directly in your double
     quoted strings –
      Escape sequence                                  Meaning
             \\                                        Backslash
              \"                                       Single quote
      La                                              Double quote
      \b                                              Alert or bell
      \f                                              Backspace
      \n                                              Form feed
      \r                                              Newline
      \t                                              Carriage return
      \v                                              Horizontal tab
      \0nn                                            Horizontal tab
      \xnn
      \cX
      \u
      \l
     example
     Let's see again how strings behave with single quotation and double quotation. Here we will
     use string escapes mentioned in the above table and will make use of the scalar variable to
     assign string values.
     #!/usr/bin/perl
     #This is case of interpolation. $str = "Welcome to \ntutorialspoint.com!"; print "$str\n":
     # This is case of non-interpolation. $str = 'Welcome to \ntutorialspoint.com!"; print "$str\n";
     #Only W will become upper case. $str = "uwelcome to tutorialspoint.com!"; print "$strin":
     #Whole line will become capital. $str = "\UWelcome to tutorialspoint.com!"; print "$str\n";
     # A portion of line will become capital. $str = "Welcome to \Ututorials point\E.com!"; print
     "$str\n";
     #Backsalash non alpha-numeric including spaces. $str = "\QWelcome to tutorialspoint's
     family": print "$str\n";
     This will produce the following result-
     Welcome to
     tutorialspoint.com!
     Welcome to \ntutorialspoint.com!
     Welcome to tutorialspoint.com!
     WELCOME TO TUTORIALSPOINT.COM!
     Welcome to TUTORIALSPOINT.com!
     Welcome to tutorialspoint\'s family
     String constants can be enclosed in single or double quotes. The string is terminated by the first
     next occurance of the quote which started it, so a single-quoted string can include double quotes
     and vice versa. The q (quote) and qq (double quote) operators allow you to use any character
     as a quoting character. Thus q/any string orq (any string) are the same as 'any string' and qq/any
     string / or qq (any string) are the same as "any string"
     Assignment:
     Borrowing from C. Perl uses '=' as the assignment operator. It is important to note that an
     assignment statement returns a value, the value assigned. This permits statements like Sb4+(Sa
     = 3);
     which assigns the value 3 to $a and the value 7 to $b.If it is required to interpolate a variable
     value without an intervening space the following syntax, borrowed from UNIX shell scripts, is
     used: Sa = "Java:
     Sb = "Sa Script"; which gives $b the value "JavaScript".
     <STDIN> - a special value:
     When the 'variable' <STDIN> appears in a context where a scalar value is required, it evaluates
     to a string containing the next line from standard input, including the terminating newline. If
     there is no input queued, Perl will wait until a line is typed and the return keypressed. The
     empty string is treated as false in a Boolean context. If <STDIN> appears on the right-hand
     side of an assignment to a scalar variable, the string containing the input line is assigned to the
     variable named on the eft. If it appears in any other scalar context the string is assigned to the
     anonymous variable: this can be accessed by the name $ many operations use it as a default.
     Scalar Expressions:
     Scalar data items are combined into expressions using operators. Perl has a lot of operators,
     which are ranked in 22 precedence levels. These are carefully chosen so that the 'obvious"
     meaning is what You get, but the old advice still applies: if in doubt,use brackets to force the
     order of evaluation. In the following sections we describe the available operators in their natural
     groupings-arithmetic. strings, logical etc.
     Arithmetic operators:
     Following the principles of 'no surprises' Perl provides the usual
     Arithmetic operators, including auto-increment and auto-decrement operators after the manner
     of C: note that in Sc=17: $d++$c:
     The sequence is increment and the assign, whereas in Sc=17; $d = $c++;
     The sequence is assign then increment. As C, binary arithmetic operations can be combined
     with assignment, e.g. Sa += 3:
     This adds 3 to Sa, being equivalent to Sa=$a+3;
     As in most other languages, unary minus is used to negate a numeric value; an almost never-
     used unary plus operator is provided for completeness.
     String Operators
     Perl provides very basic operators on strings: most string processing is one using built-in
     functions expressions, as described later.
     Unlike many languages use as a concatenation operator for strings, Perl uses a period for this
     purpose: this lack of overloading means that an operator uniquely determines the context for
     its operands.
     The other string operator is x, which is used to replicate strings, e.g.
     Sa-"Hello" x 3;
     The capability of combining an operator with assignment is extended to string operations. E.g.
     Sets Sa to "Hello Hello Hello".Sfoo"":
     Appends a space to $foo.
     So far, things have been boringly conventional for the most part. However, we begin to get a
     taste of the real flavor of perl when we see how it adds a little magic when some operators,
     normally used in arithmetic context, are used in a string context.
     Two examples illustrate this.
     1.Auto increment:
     If a variable has only ever been used in a string context, the auto increment operator can be
     applied to it. If the value consists of a sequence of letters, or a sequence of letters followed by
     a sequence of digits, the auto increment takes place in string mode starting with the rightmost
     character, with 'carry' along the string. For example, the sequence
     Saa0'; $b='Az9';
     Print ++Sa,, ++Sb: "/n": Prints al Ba0.
     2. Unaryminus:
     This has an unusual effect on non numeric values. Unary minus applied to a string which starts
     with a plus or minus character returns the same string, but starting with the opposite sign. Unary
     minus applie to an identifier returns a string consists of minus prefixed to the characters of the
     identifiers. Thus if we have a variable named Sconfig with the value "foo", then-config
     evaluates the string *"- foo". This is useful, for example, in constructing command arguments
     are introduced by -
     Comparison operators:
     The value of comparisons is returned as 1 if true, and an empty string ("") if false, in accordance
     with the convention described earlier.
     Two families of comparison operators provide, one for numbers and one for strings. The
     operator used determines the context, and perl converts the operands as required to match the
     operator.
     This duality is necessary because a comparison between strings made up entirely numerical
     digits should apply the usual rules for sorting strings ASCII as a collating sequence, and this
     may not give the same result as the numerical comparison('5' <'10') returns the value true as a
     numerical comparison having been converted into (5<10) where as the string comparison ('5'
     It '10') returns false, since 10 comes before 5 in the canonical sort order for ASCII strings.
     The comparison operator ( for numbers, cmp for strings), performs a three way test, returning
     -1 for less-than, 0 for equal an +1 for greater-than.
     Note that the comparison operators are non associative, so an expression like
     Sa > $b > Sc Is erroneous
     logical operators:
     The logical operators allows to combine conditions using the usual logical operations 'not'(!,
     not), 'and' (&&,and) and 'or'(,or). Perl implements the 'and' and 'or' operators in "shortcut' mode,
     Le evaluation stops as soon as the final result is certain using the rules false &&b=false, and
     true||b=true.
     Before Perl 5,only the !, && and || operators were provided. The new set, not, and, or, are
     provided partly to increase readability, and partly mit
     Bitwise operators:
     The unary tilde(-) applied to a numerical argument performs bitwise. negation on its operand,
     generating the one's compliment. If applied to a string operand it complements all the bits in
     the string - effective way of inverting a lot of bits. The remaining bitwise operators & (and), |
     (or) and (exclusive or)- have a rather complicated definition. If either operand is a number or a
     variable that has previously been used as a number, both operands are converted to integers if
     need be, and the bitwise operation takes place between the integers. If the both operands are
     strings, and if variables have never been used as numbers. Perl performs the bitwise operation
     between corresponding bits in the two strings, padding the shorter strings with zeros as
     required.
     Conditional expressions:
     A conditional expression is one whose values is choosen from two alternatives at run-time
     depending on the outcome of a test. The syntax is borrowed from C:
     Test? true_exp: false_exp
     The first expression is evaluated as Boolean value if it returns true the whole expression is
     replaced by true_exp,otherwise it is replaced by false_exp. e.g.
     Conditional Statement
     A Perl if statement consists of a boolean expression followed by one or more statements.
     Syntax
     The syntax of an if statement in Perl programming language is –
     if(boolean expression)
     {
     #statement(s) will execute if the given condition is true
     }
     If the boolean expression evaluates to true then the block of code inside the if statement will
     be executed. If boolean expression evaluates to false then the first set of code after the end of
     the if statement (after the closing curly brace) will be executed.
Flow Diagram
If condition is true
                                          Conditio
                                          n
                       If condition
                          Is true                                Conditional code
     Example
     #!/usr/local/bin/perl
     $a 10:
     #check the boolean condition using if statement
     if( Sa 20) (
Flow Diagram:
If condition is true
Condition
                      If condition
                        Is false                              If code
else code
     Example
     #!/usr/local/bin/perl
     $a = 100;
     #check the boolean condition using if statement
     if($a <20) # if condition is true then print the following
     printf "a is less than 20\n"; else
     # if condition is false then print the following printf "a is greater than 20\n";
     print "value of a is: $a\n";
     $a="":
     # check the boolean condition using if statement
     if($a)
     # if condition is true then print the following printf "a has a true value\n";
     else {
     a is greater than 20
     value of a is: 100
     a has a false value
     value of a is:
     An if statement can be followed by an optional elsif... else statement, which is very useful to
     test the various conditions using single if...elsif statement.
     When using if, elsif, else statements there are few points to keep in mind.
     An if can have zero or one else's and it must come after any elsif's.
     An if can have zero to many elsif's and they must come before the else.
     Once an elsif succeeds, none of the remaining elsif's or else's will be tested.
     Syntax
     The syntax of an if...elsif...else statement in Perl programming language is -
     if(boolean_expression 1){
     # Executes when the boolean expression 1 is true }elsif(boolean_expression 2) {
     # Executes when the boolean expression 2 is true } elsif(boolean_expression 3) {
     # Executes when the boolean expression 3 is true }
     else {
     #Executes when the none of the above condition is true}
     Example
     #!/usr/local/bin/perl
     $a = 100;
     # check the boolean condition using if statement if($a = 20)|
     # if condition is true then print the following
     printf "a has a value which is 20\n";
     } elsif( $a == 30) {
     #if condition is true then print the following
     A switch statement can have an optional else case, which must appear at the end of the switch.
     The default case can be used for performing a task when none of the cases is matched.
     If a case block executes an untargeted next, control is immediately transferred to the statement
     after the case statement (ie., usually another case), rather than out of the surrounding switch
     block.
     Not every case needs to contain a next. If no next appears, the flow of control will not fall
     through subsequent cases.
     Flow Diagram
expression
                                           Case 1
                                                             Code block 1
                                             Case 2
                                                             Code block2
                                             default
                                                              Code block N
     Example
     #!/usr/local/bin/perl
     use Switch:
     $var = 10:
     @array = (10, 20, 30):
     %hash = ('key l' => 10, 'key2' => 20);
     switch($var) {
     case 10 { print "number 100\n" }
     case 10 case "a" { print “string a” }
     case [1..10,42] { print "number in list" }
                                                                               de
                                                                       If True
                                                      Condition
     CStart
                         Initialization
                                                      checking
If false
                                                      End
     A for loop works on a predefined flow of control. The flow of control can be determined by
     the following:
     Init Statement: This is the first statement which is executed. In this step, we initialize a
     variable which controls the loop.
     condition: In this step, the given condition is evaluated and the for loop runs if it is True. It is
     also an Entry Control Loop as the condition is checked prior to the execution of the loop
     statements.
     Statement execution: Once the condition is evaluated to true, the statements in the loop body
     are executed.
     Increment/Decrement: The loop control variable is changed here (incremented or
     decremented) for updating the variable for next iteration. Loop termination: When the
     condition becomes false, the loop terminates marking the end of its life cycle.
     Loop termination: When the condition becomes false , the loop terminate making the end of
     its life cycle.
     Example:
     # Perl program to illustrate
     # the for loop
     for (Scount=1; $count <=3; $count++)
     }
     # for loop
     print "Scripting Language \n"
     Output:
     Scripting Language
     Scripting Language
     Scripting Language
     Foreach Loop
     A foreach loop is used to iterate over a list and the variable holds the value of the elements of
     the list one at a time. It is majorly used when we have a set of data in a list and we want to
     iterate over the elements of the list instead of iterating over its range. The process of iteration
     of each element is done automatically by the loop.
     Syntax: foreach variable
     {
     #Code to be Executed
     }                                             List
     Flow Chart:
                                                   Next
                                                 Element
                      false
Code to be execution
     Example:
     Perl
     # Perl program to illustrate
     # the foreach loop
     # Array @data = ('script'. 'FOR', 'perl');
     # foreach loop
     foreach $word (@data)
     print $word }
     Output:
     scriptFORperl
     while Loop
     A while loop generally takes an expression in parenthesis. If the expression is True then the
     code within the body of while loop is executed. A while loop is used when we don't know the
     number of times we want the loop to be executed however we know the termination condition
     of the loop. It is also known as a entry controlled loop as the condition is checked before
     executing the loop. The while loop can be thought of as a repeating if statement.
     Syntax:
     while (condition)
     { #Code to be executed
     Flow Chart:
                                                  If true
     Start                          Condition                             Statement
                                    Checking
If false
     Example:
     Perl
     # Perl program to illustrate
     .
     .
     .
     .
     .
     do.... while loop
     A do.. while loop is almost same as a while loop. The only difference is that do..while loop
     runs at least one time. The condition is checked after the first execution. A do..while loop is
     used when we want the loop to run at least one time. It is also known as exit controlled loop
     as the condition is checked after executing the loop.
     Syntax:
     do {
     #statements to be Executed
     } while(condition);
     Flow Chart:
     start
                                                                 Condition
                     statement                                   checking
                                                                         if false
end
     Example:
     Perl
     #Perl program to illustrate
     #do..while Loop
     $a = 10;
     #do.. While loop
     do {
     print "$a";
                                                 If false
     start                      Condition                                 Statememt
                                checking
                                       if true
     Example:
     Perl
     # Perl program to illustrate until Loop
     $a = 10;
     # until loop until ($a < 1)
     print "$a"; $a = $a - 1;
     Output: 10 98 7 6 5 4 3 2 1
     Nested Loops
     A nested loop is a loop inside a loop. Nested loops are also supported by Perl Programming.
     And all above-discussed loops can be nested.
     Syntax for different nested loops in Perl:
     Nested for loop
     for (init statement; condition; increment/decrement)
     {
     for (init statement; condition; increment/decrement)
     #Code to be Executed
     }
     }
     Nested foreach loop
     foreach variable_1 (@array_1)
     {
     foreach variable_2 (@array_2)
     {
     #Code to be Executed
     }
     }
     Nested while loop
     while (condition)
     {
     while (condition)
     {
     #Code to be Executed
     }
     }
     Nested do..while loop
     do {
     do {
     #Code to be Executed
     } while(condition)
     } while(condition);
     Nested until loop
     until (condition) {
     until (condition)
     {
     #Code to be Executed
     }
     }
     Example:
     Perl
     # Perl program to illustrate
     # nested while Loop
     $a = 5:
     $b=0;
     # outer while loop
     while (\$a<7)
     { Sh=0
     # inner while loop
     while ($b <7)
     {
     print "value of a = $a, b = $b\n";
     $b=Sb+1
     $a = $a + 1;
     print "Value of a = $a\n\n";
     Output:
     value of a = 5. b=0
     value of a = 5, b =1
     value of a=5. b=2
     value of a 5. b=3
     value of a=5. b=4
     value of a=5, b=5
     value of a = 5, b=6
     Value of a=6
     value of a=6 b=0
     Note: qw stands for quoted words, by using qw you can avoid the quote marks and you type
     less.
     While learning Perl, you may come accross few examples, where you see the following kind
     of array definition:
     @friends = qw/Ajeet Chaitanya Rahul/; #same as above
     This is because Perl lets you choose any punctuation character as delimiter.
     All the following statements are same:
     @friends = qw/Ajeet Chaitanya Rahul/; #same as above This is because Perl lets you choose
     any punctuation character as delimiter.
     All the following statements are same:
     @friends = qw/Ajeet Chaitanya Rahul/;
     @friends = qw! Ajeet Chaitanya Rahul!; @friends = qw;
     @friends = qw{Ajeet Chaitanya Rahul);
     @friends = qw[Ajeet Chaitanya Rahul];
     Note: The opening and closing delimiter must be same.
     Access array element
     You must have used arrays in another programming langauge like C, C++, Java etc. The basic
     concept of array is same here. Lets take an example to understand how to define an array and
     how to access the elements of it.
     #!/usr/bin/perl
     @friends = ("Ajeet", "Chaitanya", "Rahul");
     print "\Sfriends[0] = $friends[0]\n";
     print "\$friends[1] = $friends[1]\n";
     print "\Sfriends[2] = $friends[2]\n";
     Output:
     $friends[0] = Ajeet
     $friends[1] = Chaitanya
     $friends[2] = Rahul
     As you can see in the above program that arrays are prexied with @symbol. Since, individual
     array elements are nothing but scalars, they are prexied with $ symbol.
     Range operator
     Range operator is denoted by double dots "..". This operator is used for creating sequential lists.
     For example:
     #!/usr/bin/perl
     @num = (3..9); # same as (3, 4, 5, 6, 7, 8, 9)
     foreach Stemp (@num) {
     print "Stemp\n"
     Output:
     foreach Stemp (@num) { print "Stemp\n";
     }
     Output:
     3
     4
     5
     3
     5
     6
     8
     9
     Lets take few more examples to understand the range operator:
     (2.9..7.9) # same as (2, 3, 4, 5, 6, 7), values after decimal are truncated
     (9..3) # empty list, only works in increasing order
     (1, 3..6, 10, 12..14) # same as (1, 3, 4, 5, 6, 10, 12, 13, 14),
     Operators:
     pop and push : pop operator removes the last element from an array and returns it. Lets take
     an example to understand how pop operator works:
     #!/usr/bin/perl
     @num = (3..7); # same as (3, 4, 5, 6, 7)
     $n1 = pop(@num); # Sn1 is 7, array is (3, 4, 5, 6)
     $n2 = pop(@num); # Sn2 is 6, array is (3, 4, 5)
     print "\$n1 is: $n1\n";
     print "\Sn2 is: $n2\n";
     print "array now has:\n";
     @myarray = qw(Rahul, Joe, Ajeet, Tim, Lisa); @myvar = splice @array, 2, 0, qw(Harsh,
     Alisha);
     # removes nothing
     # inserts the provided list at the starting point
     #@myarray is qw(Rahul, Joe, Ajeet, Harsh, Alisha, Tim, Lisa)
     #@myvar is qw()
     The reverse Operator
     The reverse operator takes an array of elements (or list) as input and returns it in reverse order.
     For example:
     @myarray = 10..15; # same as (10, 11, 12, 13, 14, 15) @myarray2 = reverse @myarray; #
     @myarray2 has (15, 14, 13, 12, 11, 10)
     @myarray3 = reverse 5..9; # @myarray3 has (9, 8, 7, 6, 5)
     suppose you want to reverse the elements of an array and store it into the same array:
     @myarray = 10..15;
     @myarray = reverse @myarray;
     Note: If you simply write the following statement then it wont work.
     reverse @myarray;
     Perl String
     Strings are an essential part of the Perl language. They are scalar variables, so they start with
     ($) sign. A string can be defined within a single quote (') or double quote (").
     Perl String
     Strings are an essential part of the Perl language. They are scalar variables, so they start with
     ($) sign. A string can be defined within a single quote (') or double quote (").
     Perl String Operators
     The operators make it easy to manipulate a string in different ways. There are two types of
     string operators:
     Concatenation (.)
     Repetition (x)
     Perl Concatenation Operator
     Perl strings are concatenated with a (.) sign instead of (+) sign.
     1. $firstName = "Christian";
     2. $lastName = "Grey";
\a Bell
\b Gives a backspace
        Strings can be placed within a single quote (') or double quote (") but they have little
        different behavior.
     1. my $user = 'Ana';
     2. print 'Hello $user, welcome at our site.\n';
     3. print "\n";
     4. my $user = 'Ana';
     5. my $day = "today";
     6. print "Hello $user, welcome at our site $day.\n";
Output:
        Double quote provides interpolation. Means other variables present inside the string
        will represent their values. Escape characters will be replaced by their values like '\n'
        will display a new line.
     Strings can be placed within a single quote (') or double quote (") but they have little different
     behavior.
     1. my $user = 'Ana';
     2. print 'Hello $user, welcome at our site.\n';
     3. print "\n";
     4. my $user = 'Ana';
     5. my $day = "today";
     6. print "Hello $user, welcome at our site $day.\n";
     Output:
     Hello $user, welcome at our site.\n
     Hello Ana, welcome at our site today.
     In single quote, all the characters are interpreted as it is.
     Double quote provides interpolation. Means other variables present inside the string will
     represent their values. Escape characters will be replaced by their values like "\n' will display
     new line.
     Perl substr() Example
     The substr() function is used to truncate the strings. We need to provide an offset string. String
     will be truncated till the provided offset value.
     Mentioning length with the offset will print the string after offset value and till the mentioned
     length.
     If you provide a new string with offset and length, it will replace the string after offset till the
     length value.
     1. use strict;
     2. use warnings;
     3. # Original string
     4. my $originalstring = "Our site javaTpoint provides all type of tutorials";
     5. print "$originalstring\n";
     6. # Offset of 4
     7. my $offset = substr($originalstring, 4);
     8. print "$offset\n";
     9. # Offset of 4, length 15
     10. my $offsetlength = substr($originalstring, 4, 15);
     11. print "$offsetlength\n";
     12. # Replacing length with the new string
Output:
      M                If string has a new line character, the $ and ^ will match against a new line
                       boundary instead of string boundary
     The matching operator =~ is used to match a word in the given string. It is case sensitive, means
     if string has a lowercase letter and you are searching for an uppercase letter then it will not
     match.
Output:
           Matching
           Not Matching
           It is the opposite of the earlier one (=~). If the letters match it gives the output as not matched
           and vice versa.
Output:
           Not Matching
           Matching
     1. $_ = "This is javaTpoint.";
     2.      if (/java/) {
     3.          print "Matching\n";
     4.      }
     5.      else {
     6.          print "Not Matching\n";
     7.      }
     8. if (/Java/) {
     9.          print "Matching\n";
     10.     }
     11.     else {
     12.         print "Not Matching\n";
     13.     }
Output:
           Matching
           Not Matching
The matching operator m is also used to match a word in the given string.
Output:
          Matching
          Not Matching
The $1, $2 will print the word according to the specified bracket.
          1. my $word = "CuNaHg";
          2. $word =~ /(((Cu)(Na))(Hg))/;
          3. print "1: $1 2: $2 3: $3 4: $4 5: $5 6: $6\n";
Output:
1: CuNaHg 2: CuNa 3: Cu 4: Na 5: Hg 6:
It prints the matched character inside the bracket from a given string.
     1. my $word = "CuNaHg";
     2.     $word =~ /(?:(Cu)NaHg)/;
     3.     print "$1\n"; # prints "Cu"
     4.        $word =~ /(?:Cu(Na)Hg)/;
     5.     print "$1\n"; # prints "Na"
     6.        $word =~ /(?:CuNa(Hg))/;
     7.     print "$1\n"; # prints "Hg?
Output:
          Cu
          Na
          Hg
               The substitution operator is just an extension of the matched operator. It allows the
               replacement of text matched with some new text.
1. s/oldPattern/newPattern /;
Here we are replacing liquid with solid in the first part with s///.
In the second part, 'liquid' is replaced with 'solid' globally with s///g.
Output:
          Translation operator is similar as substitution operator. But translation does not use regular
          expression for search on replacement values.
     1. tr/oldLetter/newLetter /;
     2.
          Perl Translation Operator replacing one letter
Here, all the 'l' letters will be replaced with 'z' letters by translation operator.
Output:
Here, all the 'l' and 'i' letters will be replaced with 'z' and 'x' letters by translation operator.
Output:
        Subroutine in Perl
        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.
        sub subroutine_name {
          body of the subroutine
        }
        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.
        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.
#!/usr/bin/perl
        # Function definition
        sub Hello {
          print "Hello, World!\n";
        # Function call
        Hello();
        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
        −
#!/usr/bin/perl
        # Function definition
        sub Average {
          # get total number of arguments passed.
          $n = scalar(@_);
          $sum = 0;
        # Function call
        Average(10, 20, 30);
        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 −
#!/usr/bin/perl
        # Function definition
        sub PrintList {
          my @list = @_;
          print "Given list is @list\n";
        }
        $a = 10;
        @b = (1, 2, 3, 4);
Given list is 10 1 2 3 4
        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 −
#!/usr/bin/perl
        # Function definition
        sub PrintHash {
          my (%hash) = @_;
        name : Tom
        age : 19
        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
        −
#!/usr/bin/perl
        # Function definition
        sub Average {
          # get total number of arguments passed.
          $n = scalar(@_);
          $sum = 0;
            return $average;
        }
        # Function call
        $num = Average(10, 20, 30);
        print "Average for the given numbers : $num\n";
        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 −
#!/usr/bin/perl
        # Global variable
        $string = "Hello, World!";
        # Function definition
        sub PrintHello {
          # Private variable for PrintHello function
          my $string;
          $string = "Hello, Perl!";
          print "Inside the function $string\n";
        }
        # Function call
        PrintHello();
        print "Outside the function $string\n";
        The local is mostly used when the current value of a variable must be visible to called
        subroutines. A local just gives temporary values to global (meaning package) variables.
        This is known as dynamic scoping. Lexical scoping is done with my, which works more
        like C's auto declarations.
        If more than one variable or expression is given to local, they must be placed in parentheses.
        This operator works by saving the current values of those variables in its argument list on
        a hidden stack and restoring them upon exiting the block, subroutine, or eval.
Let's check the following example to distinguish between global and local variables −
#!/usr/bin/perl
        # Global variable
        $string = "Hello, World!";
sub PrintHello {
        # Function call
        PrintHello();
        print "Outside the function $string\n";
        There are another type of lexical variables, which are similar to private variables but they
        maintain their state and they do not get reinitialized upon multiple calls of the subroutines.
        These variables are defined using the state operator and available starting from Perl 5.9.4.
Let's check the following example to demonstrate the use of state variables −
#!/usr/bin/perl
        sub PrintCount {
          state $count = 0; # initial value
        for (1..5) {
          PrintCount();
        }
        Value of counter is 0
        Value of counter is 1
        Value of counter is 2
        Value of counter is 3
        Value of counter is 4
#!/usr/bin/perl
        {
            my $count = 0; # initial value
            sub PrintCount {
              print "Value of counter is $count\n";
              $count++;
            }
        }
        for (1..5) {
          PrintCount();
        }
        Subroutine Call Context
        The context of a subroutine or statement is defined as the type of return value that is
        expected. This allows you to use a single function that returns different values based on
        what the user is expecting to receive. For example, the following localtime() returns a string
        when it is called in scalar context, but it returns a list when it is called in list context.
        In this example, the value of $timestr is now a string made up of the current date and time,
        for example, Thu Nov 30 15:21:33 2000. Conversely −
        Now the individual variables contain the corresponding values returned by localtime()
        subroutine.