Perl ARGV

@ARGV and %ENV

The built-in array @ARGV contains the command line arguments for a Perl program. The following run of the Perl program critic.pl will have the ARGV array (“-poetry”, “poem.txt”).

unix% perl critic.pl -poetry poem.txt

%ENV contains the environment variables of the context that launched the Perl program.

@ARGV and %ENV make the most sense in a Unix environment.

So for example you have a script like test.pl

  #!/usr/bin/perl  use strict;  my $column=$ARGV[0];  my $database=$ARGV[1];    ------run the program now---  $./test.pl ssn employees  

in above example we are passing two values as commandline arguments. so $column will have “ssn” and $database will have “employees”.
Note: Pass values in quoutes if values have spaces.

Perl Hash Maps

Perl Hash Maps/associative arrays

ASSIGNING HASH VALUES

  • hash tables consist of key/value pairs
  • every key is followed by a value

    values can be assigned to hash tables as

      %states=  ("California","Sacramento","Wisconsin","Madison","New York","Albany");  

    We can also use => operator to identify the

    key to the left, and the value to the right; if the => operator

    encounters bare words in key positions, they will be automatically

    quoted (note “New York”, however, which consists of two words

    and MUST be quoted

      %states=  (California=>"Sacramento",Wisconsin=>"Madison","New York"=>"Albany");  

    In above example California is key and Sacromento is value.

    Similarily Wisconsin is key and Madison is value.

    Printing:

      print "Capital of California is " . $states{"California"} . "nn";  

    printing all values(using for loop):

      #!/usr/bin/perl  %states=  (California=>"Sacramento",Wisconsin=>"Madison","New York"=>"Albany");  foreach my $keys(keys %states)  {    print "KEY:$keys VALUE:$states{$keys}n";    }    output  KEY:Wisconsin VALUE:Madison  KEY:New York VALUE:Albany  KEY:California VALUE:Sacramento  
  • Perl Arrays

    Arrays @

    Array constants are specified using parenthesis ( ) and the elements are separated with

    commas. Perl arrays are like lists or collections in other languages since they can grow

    and shrink, but in Perl they are just called “arrays”. Array variable names begin with the

    at-sign (@). Unlike C, the assignment operator (=) works for arrays — an independent copy

    of the array and its elements is made. Arrays may not contain other arrays as elements.

    Perl has sort of a “1-deep” mentality. Actually, it’s possible to get around the 1-deep

    constraint using “references”, but it’s no fun. Arrays work best if they just contain

    scalars (strings and numbers). The elements in an array do not all need to be the same

    type.

      @array = (1, 2, "hello");  ## a 3 element array 
    @empty = (); ## the array with 0 elements
    $x = 1; $y = 2; @nums = ($x + $y, $x - $y); ## @nums is now (3, -1)

    Just as in C, square brackets [ ] are used to refer to elements, so $a[6] is the element

    at index 6 in the array @a. As in C, array indexes start at 0. Notice that the syntax to

    access an element begins with ‘$’ not ‘@’ — use ‘@’ only when referring to the whole

    array (remember: all scalar expressions begin with $).

      @array = (1, 2, "hello", "there");   $array[0] = $array[0] + $array[1];## $array[0] is now 3   

    Perl arrays are not bounds checked. If code attempts to read an element outside the array

    size, undef is returned. If code writes outside the array size, the array grows

    automatically to be big enough. Well written code probably should not rely on either of

    those features.

      @array = (1, 2, "hello", "there");   $sum = $array[0] + $array[27];    ## $sum is now 1, since $array[27] returned undef   $array[99] = "the end";  ## array grows to be size 100   

    When used in a scalar context, an array evaluates to its length. The “scalar” operator

    will force the evaluation of something in a scalar context, so you can use scalar() to get

    the length of an array. As an alternative to using scalar, the expression $#array is the

    index of the last element of the array which is always one less than the length.

      @array = (1, 2, "hello", "there");   $len = @array;                  ## $len is now 4 (the length of @array)   $len = scalar(@array);  ## same as above, since $len represented a scalar   ## context anyway, but this is more explicit   
      @letters = ("a", "b", "c");   $i = $#letters;## $i is now 2   

    That scalar(@array) is the way to refer to the length of an array is not a great moment in

    the history of readable code. At least I haven’t showed you the even more vulgar forms

    such as (0 + @a).

    The sort operator (sort @a) returns a copy of the array sorted in ascending alphabetic

    order. Note that sort does not change the original array. Here are some common ways to sort…

      (sort @array)  ## sort alphabetically, with uppercase first   (sort {$a  $b} @array)              ## sort numerically   (sort {$b cmp $a} @array)              ## sort reverse alphabetically   (sort {lc($a) cmp lc($b)} @array)      ## sort alphabetically, ignoring case (somewhat inefficient)   

    The sort expression above pass a comparator function {…} to the sort operator, where the

    special variables $a and $b are the two elements to compare — cmp is the built-in string

    compare, and is the built-in numeric compare.

    There’s a variant of array assignment that is used sometimes to assign several variables

    at once. If an array on the left hand side of an assignment operation contains the names

    of variables, the variables are assigned the corresponding values from the right hand

    side.

    ($x, $y, $z) = (1, 2, “hello”, 4);

    ## assigns $x=1, $y=2, $z=”hello”, and the 4 is discarded

    This type of assignment only works with scalars. If one of the values is an array, the

    wrong thing happens (see “flattening” below).

    Array Add/Remove/Splice Functions

    These handy operators will add or remove an element from an array. These operators change

    the array they operate on…

    Operating at the “front” ($array[0]) end of the array…

    shift(array)
    returns the frontmost element and removes it from the array. Can be used

    in a loop to gradually remove and examine all the elements in an array left to right. The

    foreach operator, below, is another way to examine all the elements.

    unshift(array, elem)
    inserts an element at the front of the array. Opposite of shift.

    Operating at the “back” ($array[$len-1]) end of the array…

    pop(array)
    returns the endmost element (right hand side) and removes it from the

    array.

    push(array, elem)
    adds a single element to the end of the array. Opposite of pop.

    splice(array, index, length, array2)
    removes the section of the array defined by index

    and length, and replaces that section with the elements from array2. If array2 is omitted,

    splice()
    simply deletes. For example, to delete the element at index $i from an array, use

    splice(@array, $i, 1).

    Perl Operators

    Perl Operators

    In Perl, the comparison operators are divided into two classes:

    • Comparison operators that work with numbers
    • Comparison operators that work with strings

    Integer-Comparison Operators

      Operator Description            Greater than  ==       Equal to  =       Greater than or equal to  !=       Not equal to   Comparison returning 1, 0, or -1  

    Each of these operators yields one of two values:

    • True, or nonzero
    • False, or zero

    The operator is a special case. Unlike the other integer comparison operators, returns one of three values:

    • 0, if the two values being compared are equal
    • 1, if the first value is greater
    • -1, if the second value is greater

    String-Comparison Operators

    For every numeric-comparison operator, Perl defines an equivalent string-comparison operator.

      String operator Comparison operation   lt              Less than  gt              Greater than  eq              Equal to  le              Less than or equal to  ge              Greater than or equal to  ne              Not equal to !=  cmp             Compare, returning 1, 0, or -1  

    Example

      #!/usr/bin/perl   $a="coding-school.com";  $b="www.coding-school.com";  if($a eq $b)  {  print "Both are same";  }  else  {  print "Both are different";  }  

    Perl List

    List

    A list is a sequence of scalar values enclosed in parentheses. The following is a simple example of a list:

    (1, 5.3, “hello”, 2)

    This list contains four elements, each of which is a scalar value: the numbers 1 and 5.3, the string hello, and the number 2.

    Lists can be as long as needed, and they can contain any scalar value. A list can have no elements at all, as follows:

    ()

    This list also is called an empty list.

    NOTE

    A list with one element and a scalar value are different entities. For example, the list

    (43.2)

    and the scalar value

    43.2

    are not the same thing. This is not a limitation because one can be converted to or assigned to the other.

    Perl Scalars

    Perl Scalars

    The most basic kind of variable in Perl is the scalar variable.

    Scalar variables hold both strings and numbers, and are remarkable in

    that strings and numbers are completely interchangable. For example,

    the statement

    $priority =10;

    sets the scalar variable $priority to 10, but you can also assign a string

    to exactly the same variable:

    $priority = ‘high’;

    Perl also accepts numbers as strings, like this:

    $priority = ’10’;

    $default = ‘0010’;

    and can still cope with arithmetic and other operations quite happily.

    In general variable names consists of numbers, letters and underscores, but

    they should not start with a number and the variable $_ is

    special, as we’ll see later. Also, Perl is case sensitive, so

    $a and $A are different.


    Operations and Assignment

    Perl uses all the usual C arithmetic operators:

    $a = 1 + 2; # Add 1 and 2 and store in $a
    $a = 3 – 4; # Subtract 4 from 3 and store in $a
    $a = 5 * 6; # Multiply 5 and 6
    $a = 7 / 8; # Divide 7 by 8 to give 0.875
    $a = 9 ** 10; # Nine to the power of 10
    $a = 5 % 2; # Remainder of 5 divided by 2
    ++$a; # Increment $a and then return it
    $a++; # Return $a and then increment it
    –$a; # Decrement $a and then return it
    $a–; # Return $a and then decrement it

    and for strings Perl has the following among others:

    $a = $b . $c; # Concatenate $b and

    $c

    $a = $b x $c; # $b repeated $c times

    To assign values Perl includes

    $a = $b; # Assign $b to $a
    $a += $b; # Add $b to $a
    $a -= $b; # Subtract $b from $a
    $a .= $b; # Append $b onto $a

    Note that when Perl assigns a value with $a = $b it makes

    a copy of $b and then assigns that to $a. Therefore the next time you change

    $b it will not alter $a.


    Interpolation

    The following code prints apples and pears using concatenation:

    $a = ‘apples’;

    $b = ‘pears’;

    print $a.’ and ‘.$b;

    It would be nicer to include only one string in the final print statement,

    but the line

    print ‘$a and $b’;

    prints literally $a and $b which isn’t very helpful. Instead we

    can use the double quotes in place of the single quotes:

    print “$a and $b”;

    The double quotes force interpolation of any codes, including

    interpreting variables. This is a much nicer than our original statement.

    Other codes that are interpolated include special characters such as

    newline and tab. The code n is a newline and

    t is a tab.