Perl References

Perl References

I’m happiest writing Perl code that does not use references because they always give me a mild headache. Here’s the short version of how they work. The backslash operator () computes a reference to something. The reference is a scalar that points to the original thing. The ‘$’ dereferences to access the original thing. Suppose there is a string…

$str = “hello”; ## original string

And there is a reference that points to that string…

$ref = $str; ## compute $ref that points to $str

The expression to access $str is $$ref. Essentially, the alphabetic part of the variable, ‘str’, is replaced with the dereference expression ‘$ref’…

print “$$refn”; ## prints “hello” — identical to “$strn”;

Here’s an example of the same principle with a reference to an array…

@a = (1, 2, 3); ## original array

$aRef = @a; ## reference to the array

print “a: @an”; ## prints “a: 1 2 3”

print “a: @$aRefn”; ## exactly the same

Curly braces { } can be added in code and in strings to help clarify the stack of @, $, …

print “a: @{$aRef}n”; ## use { } for clarity

Here’s how you put references to arrays in another array to make it look two dimensional…

@a = (1, 2, 3); @b = (4, 5, 6);

@root = (@a, @b);

print “a: @an”; ## a: (1 2 3)

print “a: @{$root[0]}n”; ## a: (1 2 3)

print “b: @{$root[1]}n”; ## b: (4 5 6)

scalar(@root) ## root len == 2

scalar(@{$root[0]}) ## a len: == 3

For arrays of arrays, the [ ] operations can stack together so the syntax is more C like…

$root[1][0] ## this is 4

Perl if else

The if…else Statement

This statement uses a relational expression to check the validity of a condition and execute a set of statements enclosed in braces. It returns a Boolean value, true or false, according to the validity of the condition. The syntax of the if…else statement is:

  if(condition)  {  	block of statement(s);  }  else  {  	block of statement(s);  }  

In this syntax, condition is a relational expression. If the result of this expression is true, then the block of statements following the if statement is executed. Otherwise, the block of statements following the else statement is executed.

In Perl, unlike other languages, all loops and conditional constructs require statements to be enclosed in braces, even for single statements.

  #! /usr/bin/perl  print "Enter a value for a: ";  $a = ;  print "Enter a value for b: ";  $b  = ;  if ($a>$b)  {     print "a is greater than bn";  }  else  {     print "b is greater than an";  }  

In this example, the if clause checks whether $a is greater than $b. If the value of $a is greater than $b, then the result is: a is greater than b. Otherwise, the control transfers to the code following the else clause and the statement associated with the else clause is printed as a result.

The if…elsif…else Statement

This statement is used when there is more than one condition to be checked. The syntax of the if…elsif…else statement is:

  if (condition)  {  	block of statement(s);  }  elsif (condition)  {  	block of statement(s);  }  else  {  	block of statement(s);  }  

In this syntax, if the condition associated with the if clause is false, the control transfers to elsif clause that checks for the next condition. The code associated with elsif clause is executed only if the condition is true or the code associated with the else clause is executed.

  #! /usr/bin/perl  print "Enter the score of a student: ";  $score = ;  if($score>=90)  {    print "Excellent Performancen";  }  elsif($score>=70 && $score<90)  {    print "Good Performancen";  }  else  {    print "Try hardn";  }  

Perl Loop

The Loop Statements

Different loop statements in perl…

  • The for Loop
  • The foreach Loop
  • The while Loop
  • The do-while Loop
  • The until Loop

The process of executing a code block repetitively is known as

iteration. To perform iteration in applications, use the loop

statements, such as for and while.

The loop statements check a condition and repetitively execute the

enclosed statements until the condition is true. The loop

terminates only when the condition becomes invalid.

The for Loop

This loop is used to execute a given set of statements for a fixed

number of times. The syntax of the for loop is:

  for(initialization;testing;updation)  {  	block of statement(s);  }  

In these statements:

initialization: Is the code to declare and initialize the

loop counter. Loop counter is a variable to keep a check on the

number of iterations. Initialization happens only once before the

beginning of the loop.

testing: Is the code, which specifies the condition to

control the number of iterations. The loop executes until the

result of testing is true. When the condition becomes false, the

control passes to the statement following the loop.

updation: Is the code to modify the loop counter after each

iteration. It can increment or decrement the loop counter,

according to the program requirements. Updation occurs at the end

of the loop.

block of statement(s): Is the code to be executed

iteratively. This code must be enclosed within the curly braces.

Note The three expressions for initialization, condition, and

updation are optional. If you leave the condition expression empty,

the for loop will be an infinite loop.

  #! /usr/bin/perl  print "Enter a digit to create its table: ";  $a = ;  chomp($a);  for($b=1;$b<=10;$b++)  {  	print $a.' x '.$b.' = '. $a*$b."n";  }  
  • $b=1 is the initialization statement, which initializes the

    loop counter $b to 1.

  • $b<=10 is the testing statement, which checks whether the value

    stored in $b is less than or equal to 10.

  • $b++ is the updation statement, which increments the value of

    $b by 1.

    The Nested for Loop

    A for loop contained inside another for loop is called a nested for

    loop. This is used when the data is to be stored and printed in a

    tabular format having multiple rows and columns.

      #! /usr/bin/perl  for($a=0;$a<=9;$a++){          for($b=0;$b<=$a;$b++){                  print "*";          }          print "n";  }   

    In this program:

    • The outer loop works until the value of $a is less than or

      equal to 9.

    • The inner loop works until the value of $b is less than or

      equal to the value of $a.

    • The newline character n is used to enter a newline after every

      row.

    Note The nested for loops are used with multidimensional arrays.

    For more information on arrays.

    The foreach Loop

    This loop operates on arrays. An array stores multiple related

    values in a row that can be accessed easily using the foreach loop.

    The syntax of the foreach loop is:

      foreach $var_name (@array_name)  {  	block of statement(s);  }  

    In this syntax:

    • @array_name is the array whose elements are accessed using the

      foreach loop.

    • $var_name is the scalar variable that stores the value of

      element of @array_name for each iteration.

    • This loop is repeated for all the elements in the array. The

      code used for the foreach loop is:

      #! /usr/bin/perl  @names = ("George", "Jack", "Davis");  foreach $word(@names)  {  print "$wordn";  }  

    This example, when executed, prints values of all the elements in

    the @names array one-by-one using the foreach loop. The output of

    the example is shown in Figure 4-5:

    The while Loop

    There may be situations when you do not know the number of times a

    loop is to be executed. For example, an application accepts and

    stores the scores of students in a class, and you do not know the

    number of students in a class. In this example, you can use the

    while loop.


    The while loop executes as long as the condition specified is true.

    The condition can be any valid relational expression, which returns

    true or false.

    This loop is also known as Pre-Check or Pre-Tested Looping

    Construct because the condition is checked before executing the

    statement(s) in the block.

    The syntax of the while loop is:

      while (condition)  {  	block of statement(s);  }  

    In these statements, block of statement(s) is executed only if the

    condition is true.

    Note The code block must be enclosed within curly braces.

      #! /usr/bin/perl  $a = 1;  while ($a <= 10)  {  	print "$an";  	$a++;  }  

    In this example:

    • $a, the loop counter is initialized to 1.
    • The condition checks whether $a is less than or equal to 10.
    • The value of $a is incremented by 1 in each iteration using the

      post increment operator (++).

    • The loop prints the numbers from 1 to 10 until the value of $a is less than or equal to 10. When $a is incremented to 11, the condition results in false, and the loop terminates.

    The do-while Loop

    The do-while loop is used when you want to execute a code block at

    least once unconditionally, and then iteratively on the basis of a

    condition.

    In this loop, condition is tested at the end of the loop. Because

    of this, this loop is also known as Post-Check or Post Tested

    Looping Construct.

    The syntax of the do-while loop is:

      do   {  	block of statement(s);  }  while (condition);  

      #! /usr/bin/perl  $a = 2;  do  {  	print "$an";  	$a+=2;  } while ($a<=20);  

    In this example:

    • $a, the loop counter is initialized to 2.
    • The loop prints the value of $a and also increments it by 2.
    • The condition associated with while tests whether the value of

      $a is less than or equal to 20.

    • The loop prints even numbers until the value of $a is less than

      or equal to 20. When $a is equal to 22, the loop terminates.

    The until Loop

    In case of the while loop, the code that follows condition is

    executed only if the condition is true. In the case of the until

    loop, code associated with the condition is executed only if the

    condition is false. The syntax of the until loop is:

      until(condition)  {  	block of statement(s);  }  

    In this syntax, the block of statement(s) is executed only when the

    condition returns false.

      #! /usr/bin/perl  $a = 1;  until(a == 11)  {  	print $a."n";  $a++;  }  

    In this program:

    • $a, the loop counter is initialized to 1.
    • The condition checks whether $a is equal to 11.
    • The loop prints and increments the value of $a.
    • The condition returns false until $a is less than 11, and the

      code in the loop prints from 1 to 10. The moment $a is equal to 11,

      the condition is met and loop is terminated.

  • 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.

    PHP Files

    PHP File handling

    PHP includes a lot of built-in functions for handling files and directories. You can read, write, delete, and get lots of information on files thru the use of these functions. Note that before you start working with files, you have to make sure that you have the right permissions that will allow you to manipulate them. So while you’re trying to figure out why you can’t delete a file, it may be because the server doesn’t allow you to do that.

    The creation and removal of files are completed with two functions: “touch()” and “unlink()”. “touch()” searches if a file exists, and if it doesn’t, it creates one, according to the specified filename; “unlink()” is used to remove the file passed on as an argument:

    touch(“newinfo.txt”); //create a new file, if it doesn’t already exist unlink(“oldinfo.txt”); //delete a file 

    Now that you know how to create a file, you should learn how to access it. This is done using the “fopen()” function, with requires a string containing the file path and a string containing the mode in which the file is about to be opened, which tells “fopen()” to open a file for reading, writing, or both. The complete list of the available modes can be found in the PHP documentation. “fopen()” return an integer, also known as a file pointer, which should be assigned to a variable. This will be used later on to work with the opened file. If a file cannot be open for whatever reason, “fopen()” returns FALSE. After you’re done with the file, you should remember to close it with “fclose()”, passing as an argument the file pointer.

    $oldfp = fopen(“oldinfo.txt”, “r”); //opens a file for reading if(!$fp = fopen(“newinfo.txt”, “w”)) //tries to open a file for writing die(“Error opening file!”); //terminates execution if it cannot open the file fclose($oldfp); 

    Reading from files is done with “fgets()”, which reads data from a file until it reaches a new line “n”, an EOF (end-of-file), or a specified length, in this order. So if you specify 4096 bytes but “fgets()” first reaches a new line, it stops further reading. You should know that after each reading or writing to a file, PHP automatically increments an index which holds the current position in the file. So if you have just opened a file, and then read 100 bytes, the next time you will want to read something else using the same file pointer, PHP will continue from where the 101st byte. The “fgetc()” is similar to “fgets()”, except that it returns only a single character from a file every time it is called. Because a character is always 1 byte in size, “fgetc()” doesn’t require a length argument.

    $text = fgets($fp, 2000); //reads 2000 bytes at most $chr = fgetc($fp); //reads 1 byte only 

    While you can read lines using “fgets()”, you need a way of telling when you have reached the end-of-file, so you won’t continue reading without any results. This is accomplished with the “feof()” functions, which returns “TRUE” or “FALSE”, weather the position of a file pointer is at the end of it. You now have enough information to read a file line by line:

    $filename = "test.txt"; $fp = fopen($filename, "r") or die("Couldn’t open $filename"); while(!feof($fp)) {   $line = fgets($fp);   print "$line
    "; } fclose($fp);

    While “fgets()” works well around text files, you may sometimes want more functionality for your script. The “fread()” functions returns the specified amount of data from a file, and doesn’t take into consideration the end-of-line “n”, like “fgets()”. “fread()” also starts from the current file position, but if you’re not happy with it, you can always change it using the “fseek()” function.

    fseek($fp, 100); //moves the file pointer to the 100th byte print(fread($fp, 15)); //outputs 15 bytes 

    Any writing to a file is done with the use of “fwrite()” or “fputs()” functions, which both use a file pointer and a string to perform the writing:

    fwrite($fp, “Hello from PHP!”);  fputs($fp, “Hello again from PHP!”); 

    So far, these functions were great with a single user. However, on public web-sites, with many users accessing your scripts at the same time, your files could quickly become corrupt. PHP offers the “flock()” function, which will lock a file and won’t allow other processes to write or read the file while the current process is running. “flock()” requires a file pointer and an integer to do this:

    flock($fp1, 1); //shared lock – allows read, doesn’t allow write  flock($fp2, 2); //exclusive lock – doesn’t allow neither read, nor write  flock($fp3, 3); //release lock – releases a shared or exclusive lock 

    There are a lot of other functions that you can use with files like: testing functions – “file_exists()”, “is_file()”, “is_dir()”, “is_readable()”, “is_writeable()”, “is_executable()”; functions that return information on files: “filesize()”, “fileatime()”, “filemtime()”, “filectime()”. You can figure out what the function does by just reading its name; more information about them can be found in the PHP documentation.