-> Perl is weakly typed language. $a=10; $b="a"; $c=$a.$b; print $c; output: 10a -> It follows both procedural and object oriented paradigm. Ex: Csc01BuildUnit.pm -> Base class = Build.pm ^ ^ | | Derived class Base class With .pm extension is for perl module -> Perl is interpreted language, but as compare to interpreted language like bash, etc, perl can be compiled to bytecode. -> Perl can support .pl or .PL extension, but not restricted to these only can also use .pm extension, which used in Tejas Networks. -> '#!/usr/bin/env perl': Will search for perl in $PATH environment variable from shell and then run from that The path mentioned is path for binary 'env' which is used to find exectuable for perl Use command 'which perl' to find the location of perl -> '#!/usr/bin/perl': This will be used in direct path for perl exectuable( absence of this can lead to error.) flags: -d: debugging mode(suboption: next, run, step, print, etc). * h: help * run: start execution * next: next line * step: follow function call if there * print: non-nested printing * x: nested printing of objects, data structures, etc * b: set break points * c: continue -I Directory: (include directory): Specifies @INC It add specific directories to @INC array -w: Shows important warnings -W: Shows all warnings -X: Disable all warnings @INC: It is a array of include directory. While running the scripts, we might see this in error logs. This means that some include directories are missing. -> -e "program": Runs perl script sent in as a program(Interactive mode programming). To run a one liner perl command use -e flag perl -e 'print "Hello World\n"' Output: Hello World -> eval perl: To run multi line perl command use eval perl. For example: eval perl @a = ('csc01', 'csc02', 'cef8'); print @a, "\n"; print "@a\n"; CTRL+D -> -t && -T && -U: For security & taint check/warnings. * -T: check for unsecure operation tainting in given perl script and treat them as fatal errors. Stop the scripts * -t: small brother of -T, run the scripts with warnings * -U: Allow unsecure and run scripts without warnings and errors. -> Comments: Begins with '#' symbol. '#' is used for single line comment. Multi-line comment is achieved using: =begin ..... comments ..... =cut exception: '#!/usr/bin/perl' Shabang is not comment. It just tell the bash that its a perl script. -> Whitespace: Like C, perl script does not care about whitespaces, unless they are inside the quoted strings, then they would be printed as it is. -> Single/double quote: Only double quotes expand variable and special characters such as newlines \n. $a = 10; print "Value of a = $a\n" print 'Value of a = $a\n' Output: Value of a = 10 Value of a = $a\n$ This is behaviour is similar to shell scripts. -> Multi line strings $a = 10; $multiline_str = <<"END_OF_LINE_DELIMITER"; This is the syntax for multi line string and will continue until it encounters a END_OF_LINE_DELIMITER in the first line. Also see the effect of single and double quote a=$a END_OF_LINE_DELIMITER print "$multiline_str\n"; Output: This is the syntax of multi line string and will continute until it encounters a END_OF_LIN_DELIMITER in the first line. Also see the effect of single and double quote a=10 In case of : $multiline_str = <<‘END_OF_LINE_DELIMETER’; Output would differ value of a will not expand. So a=$a will come at the end. • Escape Char : Perl uses the backslash (\) as escape character . Ex: print “\$multiline_str\n"; Output : $multiline_str • Identifiers : Perl does not allow punctuation characters such as @, $, and % within identifiers. Perl is a case sensitive programming language. So $a & $A are different. -> Variable(Scalar): Mainly perl have three type of variable: * Scalar (Denoted by $ in the starting) * Array * Hashmap If strict is being used : This is mandatory to declare a variable before we use it if we use use strict statement in our script. Syntax: use strict • Scalar : defined by $ at the start. Ex: #!/usr/bin/perl $threads= 2; # An integer assignment : a numerical scalar $compilation_dir = “/home/techie/mirror/$threads"; # A string scalar double quoted $compilation_dir2 = ‘/home/techie/mirror/$threads’; # A string scalar in single quote print “threads = $threads\n"; print “compilation_dir = $compilation_dir\n"; print “compilation_dir2 = $compilation_dir2\n"; Output : threads = 2 compilation_dir = /home/techie/mirror/2 compilation_dir2 = /home/techie/mirror/$threads ###Scaler Operations#### #!/usr/bin/perl $threads= 2 + 4; # adds two numbers $image_name = “csc01_“ . “mips.img” ; # concatenate 2 strings $final_with_prefix= $threads . “_” . $image_name ; # concatenate number with string print “threads = $threads\n"; print “image_name = $image_name\n"; print “final_with_prefix = $final_with_prefix \n"; Output : threads = 6 image_name = csc01_mips.img final_with_prefix = 6_csc01_mips.img -> Multiline String and special literals: Special literals can’t be expanded. $string = 'This is a multiline string with special literals ’ . __PACKAGE__ . “_” . __FILE__ . “_” . __LINE__ . “__LINE__”; print "$string\n"; Output : This is a multiline string with special literals tUtils_train.pl_55__LINE__ -> Variable(array): Arrays, size of array & max index : Defined by @ at start. #!/usr/bin/perl @disk_cap = (50, 30, 40, ’fifty five’,66,80,90); $size_of_array_disk_cap = @disk_cap $max_index=@disk_cap - 1 @cards = (”csc01", ”xcc360g", ”xcc80g"); @line_cards = qw(cef5 cef4c xa10g) print “disk_cap = @disk_cap\n"; print “disk_cap[0] = $disk_cap[0]\n"; print “line_cards[0] = $cards[0] cards[-1] = $cards[-1]\n"; print “size of array \@disk_cap = $size_of_array_disk_cap max_index = $max_index\n"; Output : disk_cap = 50 30 40 fifty five 66 80 90 disk_cap[0] = 50 line_cards[0] = cef5 cards[-1] = xcc80g size of array @disk_cap = 7 max_index = 6 -> Sequential Number arrays: @var_20=(10..20); print "@var_20\n"; 10 11 12 13 14 15 16 17 18 19 20 Similarly, in shell we use: seq 1 5 Output: 1 2 3 4 5 -> Operation on arrays: * push: Syntax: push(@array, value) Example: @cards = (”csc01", ”xcc360g", ”xcc80g"); print "2. \@cards = @cards\n"; #add one element at the end of the array push(@cards, "csc02"); print "2. \@cards = @cards\n"; Output: 2. @cards = csc01 xcc360g xcc80g 2. @cards = csc01 xcc360g xcc80g csc02 * unshift: Syntax: unshift(@cards, "xcc80g") Example: @cards = qw(csc01 cef5 xcc360g); print "2. \@cards = @cards\n" print " push csc02\n" #add one element at the start of the array unshift(@cards, "xcc80g"); print "3. \@cards = @cards\n"; * pop: Syntax: pop(@array); Example: @cards = qw(csc01 cef5 xcc360g); print " pop\n"; # remove one element from the last of the array pop(@cards); print "4. \@cards = @cards\n" * shift: Syntax: shift(@array) Example: @cards = qw(csc01 cef5 xcc360g); print " shift\n"; # remove one element from the beginning of the array shift(@cards); print "5. \@cards = @cards\n"; -> Slicing Array elements: Syntax: @array[2,4]; or @array[1..4]; Example: @cards = qw(csc01 cef5 xcc360g cef8 cef4c); print "==========Slicing Array elements============" @group1 = @cards[2,4]; print "\@group1 : @group1\n"; @group2 = @cards[1..4]; print "\@group2 : @groups\n"; Output: ==============Slicing Array elements================ @group1 : xcc360g cef4c @group2 : cef5 xcc360g cef8 cef4c -> Joining/Splitting the array elements * Joining: Syntax: join("v", @array); v: String which would be between the elements of array #### join will return a string #### * Splitting: Syntax: split("v", $string); v: String which act a delimiter to split the give string #### split will return array of strings #### For ex: @cards = qw(csc01 cef5 xcc369g); print "============ Joining array elements to make string =============="; $csvCards = join(",", @cards); print "\$csvCards = $csvCards\n"; $dsvCards = join("--", @cards); print "\$dsvCards = $dsvCards\n"; print "============ Splitting array elements to make array ============="; @s2aCards = split("--", $dsvCards); print "\@s2aCards = @s2aCards\n"; -> my keyword: my keyword is used in perl to limit the scope of variable to particular function or any scope where it is defined. -> Sorting and Merging: * Sorting: Syntax: sort(@array); * Merging: Syntax: (@array1,@array2); For ex: @cards = qw(csc01 cef5 xcc360g); print "=========== Sorting & Merging ============"; @sortedCards = sort(@cards); print "\@sortedCards = @sortedCards\n"; @futureCards = qw(cef9 csc03); @presentNfutureCards = (@cards,@futureCards); print "\@presentNfutureCards = @presentNfutureCards\n" Output: ========== Sorting & Merging =========== @sortedCards = cef5 csc01 xcc360g @presentnfutureCards = csc01 cef 5 xcc360g cef9 csc03 -> HashMap: Syntax: @hashMap = ('key1', 'value1', 'key2', 'value2', 'key3', 'value3'); @hashMap = ('key1' => 'value1' , 'key2' => 'value2' , 'key3' => 'value3'); For ex: print "========== HashMap ==========="; %cardG1CPUarch = ('csc01, 'mips', 'xcc360g', 'ppc', 'cef4c', 'ppc'); print "\$cardG1CPUarch{'csc01'} = $cardG1CPUarch{'csc01'}\n"; print "\$cardG1CPUarch{'xcc360g'} = $cardG1CPUarch{'xcc360g'}\n"; print "\$cardG1CPUarch{'cef4c'} = $cardG1CPUarch{'cef4c'}\n"; Output: =========== HashMap =========== $cardG1CPUarch{'csc01'} = mips $cardG1CPUarch{'xcc360g'} = ppc $cardG1CPUarch{'cef4c'} = ppc print "========== HashMap ==========="; %cardG1CPUarch = ('csc01' => 'mips', 'xcc360g' => 'ppc', 'cef4c' => 'ppc'); print "\$cardG1CPUarch{'csc01'} = $cardG1CPUarch{'csc01'}\n"; print "\$cardG1CPUarch{'xcc360g'} = $cardG1CPUarch{'xcc360g'}\n"; print "\$cardG1CPUarch{'cef4c'} = $cardG1CPUarch{'cef4c'}\n"; Output: =========== HashMap =========== $cardG1CPUarch{'csc01'} = mips $cardG1CPUarch{'xcc360g'} = ppc $cardG1CPUarch{'cef4c'} = ppc -> Slicing HashMap, Key - Values - Size of hashmap, Adding/Removing from Hashmap Ex: %cardG1CPUarch = ('csc01', 'mips', 'xcc360g', 'ppc', 'cef4c', 'ppe'); print "=============Slicing Hashes================"; @cpuSlice1 = @cardG1CPUarch('csc01', 'cef4c'); print "\@cpuSlice1 = @cpuSlice1\n"; print "=============Keys & Values & size of hash=============\n" @g1Cards = keys @cardG1CPUarch; print "\@g1Cards = @g1Cards\n"; @g1CPU = values %cardG1CPUarch; print "\@g1CPU = @g1CPU\n" #everything true for arrays can be used for ex: print "\@g1CPU[2] = @g1CPU[2]\n"; $g1HashSize = @g1Cards; #donwgrading the array to scalar. print "\$g1HashSize = $g1HashSize\n"; print "===============Adding or removing elements================\n"; $cardG1CPUarch{'PCsim"} = 'i386'; @g1Cards = keys %cardG1CPUarch; print "\@g1Cards = @g1Cards\n"; @g1CPU = values %cardG1CPUarch; print "\@g1CPU = @g1CPU\n".\; print "removing cef4c from %cardG1CPUarch\n\n"; delete $cardG1CPUarch{'cef4c'}; @g1Cards = keys %cardG1CPUarch; print "\@g1Cards = @g1Cards\n"; @g1CPU = values %cardG1CPUarch; print "\@g1CPU = @g1CPU\n"; print "====================HashMap end========================" -> Ternary operator in perl For Ex: $isSimulator = ($cardG1CPUarch{'PCsim'} == 'i386') ? "Yes" : "No"; print " \$isSimulator - $isSimulator\n"; -> Branching in Perl (if-else): For ex: $a = 20; unless( $a == 30 ){ #if condition is false then print the following printf "a has a value which is not 20\n" } elseif( $a == 30 ){ #if condition is true then print the following printf "a has a value which is 30\n"; } else{ #if none of the above condition is met printf "a has a value which is $a\n"; } -> switch in Perl (switch case): #switch with fall thru. #need Switch to be installed on system using cpan For ex: use Switch; @array = (10, 20, 30); %hash = ('key1' => 10, 'key2' => 20); switch($a){ case 10 { print "number 100\n"; next; } case "a" { print "string a" } case (\@array) { print "number in list" } case (\%hash) { print "entry in hash" } else { print "previous case not true"} } -> while loop: print "==========Loop in Perl===========\n"; $a = 10; # while loop execution & continue statement. while ( $a < 15 ){ printf "Value of a: $a\n"; $a = $a + 1; } continue { $a = $a + 1; } print "while-loop ended here\n"; Output: ==========Loops in Perl============= Value of a: 10 Value of a: 12 Value of a: 14 while-loop ended here -> do - while loop: For ex: #do...while loop execution do{ printf "Value of a: $a\n"; $a = $a + 1; }while( $a < 10 ); print "do while-loop ended here\n" Output: Value of a: Value of a: 1 Value of a: 2 Value of a: 3 Value of a: 4 Value of a: 5 Value of a: 6 Value of a: 7 Value of a: 8 Value of a: 9 do while-loop ended here -> until loop: For ex: #until loop execution #negated while loop... until( $a > 17 ){ printf "Value of a: $a\n" $a = $a + 1; } printf "until-loop ended here\n"; Output: Value of a: Value of a: 1 Value of a: 2 Value of a: 3 Value of a: 4 Value of a: 5 Value of a: 6 Value of a: 7 Value of a: 8 Value of a: 9 Value of a: 10 Value of a: 11 Value of a: 12 Value of a: 13 Value of a: 14 Value of a: 15 Value of a: 16 Value of a: 17 until-loop ended here -> for loop: # for loop execution for( $a = 10 ; $a < 20 ; $a = $a + 3){ print "value of a: $a\n" } print "for-loop ended here\n" Output: value of a: 10 value of a: 13 value of a: 16 value of a: 19 for-loop ended here -> foreach loop: # foreach loop execution @list = (200, 300, 400, 500); foreach $a (@list){ print "value of a: $a\n" } print "foreach-loop ended here\n" Output: value of a: 200 value of a: 300 value of a: 400 value of a: 500 -> next & redo ( next without label ): * next: It's like a goto statement in C/C++ * redo: It's like a continue statement in C/C++ * last: It's like a break statement in C/C++ For ex: #next and redo statements in loops print "next statement example without label\n"; $a = 13; while( $a < 18 ){ $a = $a + 1; if( $a == 15 ){ #skip the iteration $a = $a + 1; #redo; next; #last: this keyword is like break statement in C/C++ } print "value of a: $a\n"; #$a = $a + 1; } Output: next statement example without label value of a: 14 value of a: 17 value of a: 18 -> next with labels: For ex: print "\nnext statement example with label\n"; $a = 0; OUTER: while( $a < 4 ){ $b = 0; print "value of a : $a\n"; INNER: while ( $b < 4 ){ if( $a == 2 ){ $a = $a + 1; #jump to outer loop next OUTER; #last OUTER; #in case of last it will throw out of all nested loop } $b = $b + 1; print "Value of b : $b\n" } print "\n"; $a = $a + 1; } Output: next statement example with label value of a: 0 value of b: 1 value of b: 2 value of b: 3 value of b: 4 value of a: 1 value of b: 1 value of b: 2 value of b: 3 value of b: 4 value of a: 2 value of a: 3 value of b: 1 value of b: 2 value of b: 3 value of b: 4 -> Function in perl: For ex: print "\n==========Subroutines in Perl=======\n\n"; print "==== Passing scalars and arrays & returning result ====\n"; sub printSum{ print "In Average's subroutine: \$n = $n\n"; print "In Average's subroutine: \$sum = $sum\n"; print "In Average's subroutine: \$average = $average\n"; } sub Average{ #get total number of arguments passed. $n = scaler(@_); # If array is passed as an argument to subroutine # use @_ or if scalar is passed as an argument use # $_. #Scope of variables: #this will be available to Average's subroutines local $sum = 0; # Any function called from Average # subroutine can access $sum variable foreach $item (@_){ $sum += $item; } printSum(); ##private variable my $average = $sum / $n; return $average; } #Function call @a = (40, 50, 60); $b = 70; $avg = Average(10, 20, 30, @a, $b); print "Average for the given numbers: $avg\n"; print "\$sum = $sum\n"; print "\$n = $n\n"; print "\$average = $average\n"; Output: ====Subroutines in Perl==== ==== Passing scalars and array & returning result === In Average's subroutine: $n = 7 In Average's subroutine: $sum = 280 In Average's subroutine: $average = Average for the given number : 40 $sum = $n = 7 $avearge = -> Passing hashes in subroutines: For ex: %cardG1CPUarch = ('csc01', 'mips', 'xcc360g', 'ppc', 'cef4c', 'ppc'); print "===== Passing hashes to subroutines ====\n"; #Function definition sub PrintHash{ my (%hash) = @_; foreach my $key ( keys %hash ){ my $value = $hash{$key}; print "$key : $value\n"; } } #Function call with hash parameter PrintHash(%cardG1CPUarch); Output: ====== Passing hashes to subroutines ====== cef4c: ppc xcc360g: ppc csc01: mips -> References in Perl: For ex: print "\n==== References in Perl =====\n\n"; $var = 10; # Now $r has reference to $var scalar. $r = \$var; # Print value available at the location stored in $r. print "Type of reference is :" . ref($r) . "\n"; print "Value of $var is: " , $$r, "\n"; @var = (1,2,3); #Now $r has reference to @var array. $r = \@var; #Print values available at the location stored in $r. print "Type of reference is :" . ref($r) . "\n"; print "Value of @var is :" . @$r, "\n"; %var = ('key1' => 10, 'key2' => 20); # Now $r has reference to $var has. $r = \%var; # Print values available at the location stored in $r. print "Type of reference is :" . ref($r) . "\n"; print "Value of %var is : " , $r, "\n"; print "Value of %var is : " , %$r{'key1'}, "\n"; Output: ====== Refernce in Perl ====== Type of reference is : SCALAR Value of 10 is : 10 Type of reference is : ARRAY Value of 1 2 3 is : 123 Type of reference is : HASH Value of %var is : key220key110 Value of %var is : key110