Perl Notes

Perl Notes

String Literals

Single quotes are blind. Perl starts from ‘ and stops the literal till ‘ blindly.

Double quotes parse the literal for special characters such as \t,\n\r,\U..\E and variables$var

\l Change the next character to lower case
\u Change the next character to upper case
\L Change the following characters to lowercase until a \E sequence is encountered. Note that you need to use an uppercase E here, lowercase will not work.
\Q Quote meta-characters as literals. See Chapter 10, “Regular Expressions” , for more information on meta-characters.
\U Change the following characters to uppercase until a \E sequence is encountered. Note that you need to use an uppercase E here, lowercase will not work.
\E Terminate the \L, \Q, or \U sequence. Note that you need to use an uppercase E here, lowercase will not work.
\\ Backslash

Eg:

$t =”Raj”;

print “hello \a\rAre you there \U$t\E?\n”; Are you there RAJ?

print ‘you are “amazing”‘; you are “amazing”

Back quoted String

When Perl sees a back-quoted string, it passes the contents to Windows, UNIX, or whatever operating system you are.

print `dir *.txt`; prints the txt files in that directory

Arrays

Number Range print (1..15); 123456789101112131415

Transpose:

@arr = (B..G);

$first = $arr[0];

$third = $arr[2];

@half = @arr[2,3];

 

print “@arr”.”\n”; B C D E F G

@arr[0, 3] = @arr[3, 0];

print “@arr”; E C D B F G

Reversing an Array:

@arr = (1..10);

$i = 0;

 

while ($i < @arr/2)

{

      @arr[$i, @arr-$i-1] = @arr[@arr-$i-1, $i]; 

      $i = $i + 1;

};

print "@arr";

Sorting an Array (Bubblesort)

@arr = (1,45,43,76,12,64);

$i = 0;

$n=@arr;

 

print "@arr\n";

for ($i=0; $i<$n-1; $i++){

      for($j=0; $j<$n-$i-1; $j++){

            if($arr[$j] > $arr[$j+1]){

                  @arr[$j, $j+1] = @arr[$j+1, $j];

                  

            }

      }

}

print "@arr";

 

Associate Array (Hashes)

@arr = (557, "Mahesh", 534, "Raj");
%assoc = @arr;
print $assoc{557};                                                            Mahesh

$ = “the” (singular)
@ = “those” (plural)
% = “relationship”

Jump Keywords

last Jumps out of the current statement block.
next Skips the rest of the statement block and continues with the next iteration of the loop.
redo Restarts the statement block.
goto Jumps to a specified label.

Last

@array = (“A”..”Z”);

for ($index = 0; $index < @array; $index++) {

if ($array[$index] eq “T”) {

last; breaks the loop

}

}

print(“$index\n”);

This program displays:

19

 

By default “last” breaks the current loop. If a label is specified for the loop, it breaks that loop specified with last

 

OUTER_LOOP:
    for ($index = 0; $index < 10; $index++) {
        if ($index == 5) {
            last;
        }
        while ($index < 10) {
            if ($index == 4) {
                last OUTER_LOOP;              Breaks the outer loop
            }
            print("inner: index = $index\n");
            $index++;
        }
       print("outer: index = $index\n");
}
print("index = $index\n");

 

Next – skip rest of stmt in block and start next iteration

Similar to keyword continue in C

Similar to Last, next OUTER_LOOP starts new iteration in loop labeled OUTER_LOOP.

Redo – It repeats the Iteration block from starting, keeping the iteration variables with same values

It is normally used for user input. If validation failsàredo the task.

{
    print("What is your name? ");
    $name = <STDIN>;
    chop($name);
 
    if (! length($name)) {
        print("Msg: Zero length input. Please try again\n");
        redo;
    }
 
    print("Thank you, " . uc($name) . "\n");
}

Goto – Not recommended…

Functions

$areaOfFirstCircle = areaOfCircle(5);
print("$areaOfFirstCircle\n");
 
sub areaOfCircle {
    $radius = $_[0];                      @_ holds the parameters passed
    return(3.1415 * ($radius ** 2));            return keyword returns the value
}

Note: @_ passes parameters by Reference

Change in @_ in function reflects change in main program

@t = (12, 34);
swap(@t);
print "@t";                   34 12
 
sub swap{
      @_[0, 1] = @_[1, 0];
}

Same holds for variables also

$a=1;
$b=2;
 
swap($a, $b);
print "$a";                 #  2
 
sub swap{
      $t = $_[0];
      $_[0]=$_[1];
      $_[1]=$t;
}

Hence use scalars instead of @_ inside functions

@array = (0..5);
print("Before function call, array = @array\n");
firstSub(@array);
print("After function call, array =  @array\n");
 
sub firstSub{
    ($firstVar, $secondVar) = @_;
 
    $firstVar = "A";                This doesnot affect the original values
    $secondVar = "B";
}

By default, all Perl variables are accessible everywhere inside a program

i.e., variable in main program can be accessed in subprogram as well and reflects the change if made.

Inorder to limit the scope perl introduced

  • The my() function creates a variable that only the current function can see.
  • The local() function creates a variable visible inside the current function and inside any functions that are called by the current function

Sub first{
      local ($a) = 12;
      my ($b) = 15;
 
              secondfunc();
 
             print “\$a = $a\n\$b=$b”;
}
sub secondfunc(){
	      $a=2000;
	      $b=1000;
	}
OUTPUT:$a = 2000 $a being local variable secondfunc (i.e chiled function) has scope and can effect $a$b = 15 $b being my variable can be accessed only by first() and cannot be manipulated by second()

Only One array can be passed to a function

You can pass as many scalar values as you want to a function, but only one array. If you try to pass more than one array, the array elements become joined together and passed as one array to the function. Your function won’t be able to tell when one array starts and another ends.

func((1..10), "AAAA");
 
sub func{
      local(@array, $var) = @_;
      
      print "Arry: @array\n";       
      print "Var : $var";           
}

Arry: 1 2 3 4 5 6 7 8 9 10 AAAA Array is exhaustive and takes everything and leaving no data items for next coming variable

Var :

Solution:

func( "AAAA", (1..10));
 
sub func{
      local( $var, @array) = @_;  Now $var  takes one data item and @array takes all next items
      
      print "Arry: @array\n";       
      print "Var : $var";           
}

So you can pass any number of scalar variables and only one list variable at the end

Private Functions

These are defined inside some scope (i.e func) and can used only in that scope

print  “Calculation : “.calc(10,10);
sub calc{
      ($v1,$v2) = @_;
      $expo = sub{                  Defined a function identified by $expo
            return  @_[0]**2;
      };
      
      return  &$expo($v1) * & $expo( $v2); I guess we are passing data to specified address containing function hence & should be placed before variable name
}
 

Output: Calculation = 10000

String Fucntions

Table 5.1-String Functions
Function Description
chomp(STRING) OR chomp(ARRAY) Uses the value of the $/ special variable to remove endings from STRING or each element of ARRAY. The line ending is only removed if it matches the current value of $/.Usually used to remove trailing $/ in user input.$var = chomp(<STDIN>);
chop(STRING) OR chop(ARRAY) Removes the last character from a string or the last character from every element in an array. The last character chopped is returned.
chr(NUMBER) Returns the character represented by NUMBER in the ASCII table. For instance, chr(65) returns the letter A.
crypt(STRING1, STRING2) Encrypts STRING1 using STRING2 as seed/password.It can be used like a hash function match
index(STRING, SUBSTRING, POSITION) Returns the position of the first occurrence of SUBSTRING in STRING at or after POSITION. If you don’t specify POSITION, the search starts at the beginning of STRING.Returns -1 is match not found.Doesn’t support Regex as substring.
join(STRING, ARRAY) Returns a string that consists of all of the elements of ARRAY joined together by STRING. For instance,$failedstudents = join(“, ” , @failedNames);returns “Hari Krishna, Ram Gopal, Raj”
lc(STRING) Returns a string with every letter of STRING in lowercase. For instance, lc(“ABCD”) returns “abcd”.
lcfirst(STRING) Returns a string with the first letter of STRING in lowercase. For instance, lcfirst(“ABCD”) returns “aBCD”.
length(STRING) Returns the length of STRING.
ord(STRING) Returns the ascii value of the first character of STRING. If STRING is omitted, then $_ is used. For instance, ord(“ABC”) returns the number 65.

Errata Note
This function has been added to the list after the printed version was completed. Its utility as a string function was initially overlooked. Randal Schwartz was kind enough to mention that it should be added.
rindex(STRING, SUBSTRING, POSITION) Returns the position of the last occurrence of SUBSTRING in STRING at or before POSITION. If you don’t specify POSITION, the search starts at the end of STRING.
split(PATTERN, STRING, LIMIT) Breaks up a STRING using PATTERN as the delimiter. The LIMIT parameter indicates how many parts to create from STRING. In an array context, it returns a list of the parts that were found. In a scalar context, the number of parts found.

LIST = split(/PATTERN/, EXPR, LIMIT);

Please note that if you use inside the pattern a metacharacter as:

^ $ ( ) \ | @ [ { ? . + *
you need to escape it by using the \ (backslash character)

$str = "Raj|Ramana|Ranga|King";
@list = split(/\|/, $str);  Regex: /\|/ since | should be escaped with \
print "@list";

Output: Raj Ramana Ranga King

We can also specify a character class for delimiter

$str = "This ?is! a  [short]-(sentence)! Why?";
@list = split(/[?,!,\-,\[,\],(,),\?]+/, $str);
Regex =  [?,!,\-,\[,\],(,),\?]+     Character class

Output: This is a short sentence why

substr(STRING, OFFSET, LENGTH) Returns a portion of STRING as determined by the OFFSET and LENGTH parameters. If LENGTH is not specified, then everything from OFFSET to the end of STRING is returned. A negative OFFSET can be used to start from the right side of STRING.$firstVar = “0123BBB789”;substr($firstVar, 4, 3) = “AAA”;

print(“firstVar = $firstVar\n”);

This program prints:  

firstVar = 0123AAA789

uc(STRING) Returns a string with every letter of STRING in uppercase. For instance, uc(“abcd”) returns “ABCD”.
ucfirst(STRING) Returns a string with the first letter of STRING in uppercase. For instance, ucfirst(“abcd”) returns “Abcd”.

Array Functions

Arrays are a big part of the Perl language and it has a lot of functions to help you work with them. Some of the actions they perform include deleting elements, checking for the existence of an element, reversing all of the the elements in an array, and sorting the elements. Table 5.2 lists the functions you can use with arrays.

Table 5.2-Array Functions
Function   Description
defined(VARIABLE) returns true if VARIABLE has a real value and false if the variable has not yet been assigned a value. This is not limited to arrays, any data type can be checked. Also see the exists function for information about associative array keys.
delete(KEY) Removes the key-value pair from the given associative array. If you delete a value from the %ENV array the environment of the current process is changed, not that of the parent.
each(ASSOC_ARRAY) Returns a two-element list that contains a key and value pair from the given associative array. The function is mainly used so that you can iterate over the associate array elements. A null list is returned when the last element has been read.
exists(KEY) Returns true if the KEY is part of the specified associative array. For instance, exists($array{"Orange"}) returns true if the %array associative array has a key with the value of “Orange.”
join(STRING, ARRAY) Returns a string that consists of all of the elements of ARRAY joined together by STRING. For instance, join(">>", ("AA", "BB", "CC")) returns "AA>>BB>>CC".
keys(ASSOC_ARRAY) Returns a list that holds all of the keys in a given associative array. The list is not in any particular order.
map(EXPRESSION, ARRAY) The Perl map function evaluates a block or an expression for each element of an array and returns a new array with the result of the evaluation. During the evaluation, it locally assigns the $_ variable to each element of the array.

my @array = map $_** 2, (1..10);
print "@array\n";
 
# it outputs: 1 4 9 16 25 36 49 64 81 100
my @array = qw(this is a perl script);
 
@array = map { uc $_ } @array; 
print "@array\n";
 
# it displays: THIS IS A PERL SCRIPT

NOTE: syntax:

map expr, @list

map {block} @list No , separater

The last example can be written as

@array = map uc $_, @array;

pack(STRING, ARRAY) Creates a binary structure, using STRING as a guide, of the elements of ARRAY
Fore More Informationhttp://www.perlmonks.org/?node_id=224666
pop(ARRAY) Returns the last value of an array. It also reduces the size of the array by one.
push(ARRAY1, ARRAY2) Appends the contents of ARRAY2 to ARRAY1. This increases the size of ARRAY1 as needed.
reverse(ARRAY) Reverses the elements of a given array when used in an array context. When used in a scalar context, the array is converted to a string, and the string is reversed.
scalar(ARRAY) Evaluates the array in a scalar context and returns the number of elements in the array.
shift(ARRAY) Returns the first value of an array. It also reduces the size of the array by one.
sort(ARRAY) Returns a list containing the elements of ARRAY in sorted order. See Chapter 8, “References,” for more information.
splice(ARRAY1, OFFSET, LENGTH, ARRAY2) Replaces elements of ARRAY1 with elements in ARRAY2. It returns a list holding any elements that were removed. Remember that the $[ variable may change the base array subscript when determining the OFFSET value.
split(PATTERN, STRING, LIMIT) Breaks up a string based on some delimiter. In an array context, it returns a list of the things that were found. In a scalar context, it returns the number of things found.
undef(VARIABLE) Slways returns the undefined value. In addition, it undefines VARIABLE which must be a scalar, an entire array or a subroutine name.
unpack(STRING, ARRAY) Does the opposite of pack().
unshift(ARRAY1, ARRAY2) Adds the elements of ARRAY2 to the front of ARRAY1. Note that the added elements retain their original order. The size of the new ARRAY1 is returned.
values(ASSOC_ARRAY) Returns a list that holds all of the values in a given associative array. The list is not in any particular
createPair("100",  "Kathy Jones");
createPair("200",  "Grace Kelly");
createPair("100", "George Orwell");
 
while (($key, $value) = each %array) {
    print("$key, $value\n");
};
 
sub createPair{
    my($key, $value) = @_;
 
    while (defined($array{$key})) {
        $key++;
    }
 
    $array{$key} = $value;
};

This program prints:  
100, Kathy Jones
101, George Orwell
200, Grace Kelly

MAP examples

open FILE,"file1.csv" or die $!;
 
@records = map {chomp; [split /,/];} <FILE>;
 
foreach $rec (@records){
      foreach $col (@{$rec}){
                  print "$col ";
      }
      print "$rec\n"
}

Inside the map block:

  • each record from the list will be assigned in turn to $_
  • the chomp function will remove the trailing newline from $_
  • the split function will split the record of the file using the ‘,‘ delimiter, returning an anonymous array having as elements the fields of the record
  • [] returns a reference to the new anonymous array returned by the split function

If [] not used bounding split /,/ then a list is returned

@records will has all the elements in every record as a single list of elements.

Parsing Hash Pairs

%stud = (100,"Raj",101,"Jack",105,"Jill");
 
foreach $key (keys(%stud)){
      print "$key -> $stud{$key}\n";            #need to use { } for hashes, [] for arrays 
}
Advertisements

About wikihead

A Seeker. Information Security Professional, Pursuing Life with Ayurveda.
This entry was posted in Notes, Tutorials and tagged , . Bookmark the permalink.

One Response to Perl Notes

  1. wikihead says:

    An alternate way to use jump keywords so that it is much simpler.

    foreach (@names){
    last if $_ =~ /mahesh/; #break the loop if name contains mahesh
    }

    Although, Splice can be used to replace elements in a array, it can be used to
    1)remove elements
    splice(@names, $i, 1); #remove one name at $i th location
    2)insert elements
    splice(@name, $i, 0, @newnames);

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s