logging in or signing up perl tutorial Jadav3000 Download Post to : URL : Related Presentations : Share Add to Flag Embed Email Send to Blogs and Networks Add to Channel Uploaded from authorPOINT lite Insert YouTube videos in PowerPont slides with aS Desktop Copy embed code: (To copy code, click on the text box) Embed: URL: Thumbnail: WordPress Embed Customize Embed The presentation is successfully added In Your Favorites. Views: 332 Category: Science & Tech.. License: All Rights Reserved Like it (2) Dislike it (0) Added: September 14, 2010 This Presentation is Public Favorites: 0 Presentation Description No description available. Comments Posting comment... By: jiten_nigam (20 month(s) ago) nice presentation sir..plz send it to me karannigam482@gmail.com thanks Saving..... Post Reply Close Saving..... Edit Comment Close Premium member Presentation Transcript Perl Training : Perl Training By Jadav Bheda What is Perl? : What is Perl? Practical Extraction and Report Language ‘A general-purpose programming language originally developed for text manipulation and now used for a wide range of tasks including system administration, web development, network programming, GUI development, and more.’ Slide 3: Parser Compiler Optimizer Interpreter Syntax Tree Unoptimized Bytecode Optimized Bytecode Fully-laden Interpreter Precompiled Bytecode What's Perl good/bad for? : What's Perl good/bad for? ‘Many earlier computer languages, such as Fortran and C, were designed to make efficient use of expensive computer hardware. In contrast, Perl is designed to make efficient use of expensive computer programmers. Good for: Quick scripts, complex scripts Parsing & restructuring data files CGI-BIN scripts High-level programming Networking libraries Graphics libraries Database interface libraries Bad for: Compute-intensive applications (use C) Hardware interfacing (device drivers…) Let's Code! : Let's Code! #!/usr/bin/perl -w #-w enables warning #use warnings; -- this could have used instead of -w # This is comment use strict; # perl is dynamic typed like VB my $name = ‘Vavni’; print “\n hello world from $name.\n”; Perl Datatypes : Perl Datatypes Scalar: a single piece of information. Scalars can hold numbers or text $ is the identifier of scalar in perl There are special variables for the system: $ARGV,$! List: an ordered collection of scalars @array = ( 1, 2 ) @words = ( "first", "second", "third" ) Hash: special arrays with words as index. %hash = (“key1” => val1, “key2” => val2); ** Don't forget undef Example of Scalar : Example of Scalar $num = 42 $num2 = “42” $name = ‘joe’ $color = “blue” $string_w_num = “I have 10 apples” $foo = “” $foo =‘’ Quoting and Interpolation : Quoting and Interpolation Double quote(“”), single quote('') and qq Example: my $var = 10; print “Value is : $var”; print 'Value is : $var”; print qq { Value is : $val }; Boolean : Boolean Undefined values are treated as false Scalars are evaluated as: numbers are evaluated as true if non-zero strings are evaluated as true if non-empty $var = “false”; if($var) { print “$var is true!\n”; } User Input / Command-line arg : User Input / Command-line arg Scripts can take inputs in two ways: Prompted inputs from users $user_text = <STDIN> Command-line Arguments ./print_args.pl ARG1 ARG2 $0 = program name @ARGV array of arguments to program Example yourprog -a somefile $0 is “yourprog” $ARGV[0] is “-a” $ARGV[1] is “somefile” Operators : Operators Math The usual suspects: + - * / $total = $subtotal * (1 + $tax / 100.0); Exponentiation: ** $cube = $value ** 3; $cuberoot = $value ** (1.0/3); Bit-level Operations left-shift: << $val = $bits << 1; right-shift: >> $val = $bits >> 8; Operators (cont..) : Operators (cont..) Assignments As usual: = += -= *= /= **= <<= >>= $value *= 5; $longword <<= 16; Increment: ++ $counter++ ++$counter Decrement: -- $num_tries-- --$num_tries Operators (cont..) : Operators (cont..) Boolean (against bits in each byte) Usual operators: & | Exclusive-or: ^ Bitwise Negation: ~ $picture = $backgnd & ~$mask | $image; Boolean Assignment &= |= ^= $picture &= $mask; Operators (cont..) : Operators (cont..) Logical (expressions) && And operator | | Or operator ! Not operator AND And, low precedence OR Or, low precedence NOT Not, low precedence XOR Exclusive or, low precedence open ( FILE, "<filename" ) || die ..... open FILE, "<filename" or die .... # Notice how the much lower # precedence of "or" makes the parenthesis unnecessary in this case. Operators (cont..) : Operators (cont..) Short Circuit Operators expr1 && expr2 expr1 is evaluated. expr2 is only evaluated if expr1 was true. expr1 || expr2 expr1 is evaluated. expr2 is only evaluated if expr1 was false. Examples open (…) || die “couldn’t open file”; $debug && print “user’s name is $name\n”; Operators (cont..) : Operators (cont..) Modulo: % $a = 123 % 10; ($a is 3) Multiplier: x print “ride on the ”, “choo-”x2, “train”;(prints “ride on the choo-choo-train”) $stars = “*” x 80; Assignment: %= x= String Concatenation: . .= $name = “Uncle” . $space . “Sam”; $cost = 34.99; $price = “Hope Diamond, now only \$”; $price .= “$cost”; Conditional Operators : Conditional Operators numeric string * Equal: == eq * Less/Greater Than: < > lt gt * Less/Greater or equal:<= >= le ge * Comparison: <=> cmp * Results in a value of -1, 0, or 1 * Zero and empty-string means False * All other values equate to True Control Structures : Control Structures “if” statement - first style if ($porridge_temp < 40) { print “too hot.\n”;}elsif ($porridge_temp > 150) { print “too cold.\n”;}else { print “just right\n”;} Control Structures (cont..) : Control Structures (cont..) “if” statement - second style statement if condition; print “\$index is $index” if $DEBUG; Single statements only Simple expressions only “unless” is a reverse “if” statement unless condition; print “millenium is here!” unless $year < 2000; Control Structures (cont..) : Control Structures (cont..) “for” loop - first style for (initial; condition; increment) { code } for ($i=0; $i<10; $i++) { print “hello\n”; } “for” loop - second style for [variable] (range) { code } for $name (@employees) { print “$name is an employee.\n”;} “for” loop with default loop variable for (@employees) { print “$_ is an employee\n”; print; # this prints “$_” } Control Structure (Cont..) : Control Structure (Cont..) “while” loop while (condition) { code } $cars = 7;while ($cars > 0) { print “cars left: ”, $cars--, “\n”;} “until” loop is opposite of “while” until (condition) { code } $cars = 7;until ($cars <= 0) { print “cars left: ”, $cars--, “\n”;} Control Structures (cont..) : Control Structures (cont..) Loop Controls “next” operator - go on to next iteration (as continue in C) “redo” operator - re-runs current iteration “last” operator - ends the loop immediately (as break in C) while (cond) { next if $a < 5;} Break out of multilevel loops using labels (as goto in C) top: while (condition) { for ($car in @cars) { … do stuff … next top if situation; }} List : List List (one-dimensional array) @memory = (16, 32, 48, 64); @people = (“Alice”, “Alex”, “Albert”); First element numbered 0 (can be changed) Single elements are scalar: $names[0] = “Ferd”; Slices are ranges of elements @guys = @people[1..2]; How big is my list? print “Number of people: $#people\n”; Some Useful Functions : Some Useful Functions push( ), pop( )- stack operations on lists shift( ),unshift( ) - bottom-based ops split( ) - split a string by separator @parts = split(/:/,$passwd_line); while (split) … # like: split (/\s+/, $_) splice( ) - remove/replace/sub str of array substr( ) - substrings of a string Some Useful Functions : Some Useful Functions length( ) - length in bytes (strings) stat( ) - file stats (times, sizes, ...) pack( ),unpack( ) - byte/record packing hex( ) - hex string to integer conv printf( ) - formatted printing sprintf( ) - printf into a string $str = sprintf (“expense = %.2f”, $expns); Hash : Hash Hash (associative array) %var = { “name” => “paul”, “age” => 33 }; Single elements are scalar print $var{“name”}; $var{age}++; How many elements are in my hash? @allkeys = keys(%var); $num = $#allkeys; Dealing with Hashes : Dealing with Hashes keys( ) - get an array of all keys foreach (keys (%hash)) { … } values( ) - get an array of all values @array = values (%hash); each( ) - get key/value pairs while (@pair = each(%hash)) { print “element $pair[0] has $pair[1]\n”;} Dealing with Hashes : Dealing with Hashes exists( ) - check if element exists if (exists $hash{$key}) { … } delete( ) - delete one element delete $hash{$key}; Subroutine : Subroutine Defined using the sub command: sub name { ... } Called from the main program or another subroutine using its name: name; Sometimes you will see in old Perl programs (like mine) &name; But is optional in modern Perl. Subroutine (cont..) : Subroutine (cont..) Subroutines can be placed anywhere in the program but best to group them at the end; # main program . . exit; # subroutines defined here sub sub1 { ... } sub sub2 { ... } sub sub3 { ... } Slide 31: All the parameters in a Perl subroutine (including arrays) end up in a single array called @_ Therefore in the code: By default the subroutine returns the last thing evaluated but you can use the return statement to make this explicit: $pos = find_motif($motif,$protein); . sub find_motif { $a = $_[0]; $b = $_[1]; ...return $b; } Subroutine (cont..) : Subroutine (cont..) What if want to pass two arrays to subroutine?(As everything arrives in the sub in a single array) $seq=compare_seqs(@seqs1,@seqs2); Solution: Use references (pointers) References (sometimes called pointers in other languages) can be more convenient because in Perl they are scalars → often much smaller than the object they refer to (e.g. an array or hash). Array references can be passed around and copied very efficiently, often also using less memory. Being scalars, they can be used to make complicated data structures such as arrays of arrays, arrays of hashes and so on.. Subroutine (cont..) : Subroutine (cont..) Simplest way to create a reference in Perl is with \ To get back the original object the reference needs to be dereferenced; $scalar_ref = \$sequence; # reference to a scalar $dna_ref = \@DNA_list; # reference to an array $hash_ref = \%genetic_code; # reference to a hash $scalar = $$scalar_ref; # for scalars just add $ @new_dna = @$dna_ref; # for arrays just add @ %codon_lookup = %$hash_ref; # similary for hashes Subroutine (cont.. ) : Subroutine (cont.. ) Solution to two array problem # compare two databases, each held as an array # $results = compare_dbase(\@dbase1,\@dbase2); # supply refs ... sub compare_dbase { my ($db1_ref,$db2_ref) = @_; # params are refs to arrays @db1 = @$db1_ref; # dereference @db2 = @$db2_ref; # dereference ... # now use @db1,@db2 return $results; } Variable Scope : Variable Scope Perl has two types of scope Package scope Package scope is default scope Global scope; exist through out program life Use 'our' for strict definition Local scope (my, local) Use 'my' to declare local variables my $var=5; My ($one, $two, @three) = (1, 2, @_); Local is temporary global (it's history) http://perl.plover.com/FAQs/Namespaces.html#Package_Variables Slide 36: My Vs Local $lo = 'global'; $m = 'global'; A(); sub A { local $lo = 'AAA'; my $m = 'AAA'; B(); } sub B { print "B ", ($lo eq 'AAA' ? 'can' : 'cannot')," see the value of lo set by A.\n"; print "B ", ($m eq 'AAA' ? 'can' : 'cannot')," see the value of m set by A.\n"; } This prints B can see the value of lo set by A. B cannot see the value of m set by A. Local static (as in C) : Local static (as in C) Local static implementation in perl: { my $seed = 1; sub my_rand { $seed = int(($seed * 1103515245 + 12345) / 65536) % 32768; return $seed; } } $seed will be created only a first time when outer block executes, not every time when my_rand subroutine executes. Basic File I/O : Basic File I/O Reading a File open (FILEHANDLE, “$filename”) or die “Reading of file $filename failed: $!”;while (<FILEHANDLE>) { chomp $_; # or just: chomp; print “$_\n”;}close FILEHANDLE; Basic File I/O : Basic File I/O Writing a File open (FILEHANDLE, “>$filename”) or die “Writing to file $filename failed: $!”;while (@data) { print FILEHANDLE “$_\n”; # note, no comma!}close FILEHANDLE; Basic File I/O : Basic File I/O Predefined File Handles <STDIN> input <STDOUT> output <STDERR> output print STDERR “big bad error occurred\n”; <> ARGV or STDIN Basic File I/O : Basic File I/O How does <> work? opens each ARGV filename for reading if no ARGV’s, reads from stdin great for writing filters, here’s “cat”: while (<>) { print; # same as print “$_”;} File Test Operators : File Test Operators Existence: if (-e “file”) Readable, Writable, Executable: -r -w -x Zero size file, non-zero size file: -z -s Plain File, Directory, Symlink: -f -d -l Named Pipe, Socket: -p -S TTY attached: -t if (-t STDIN) # is stdin a terminal or not? File Functions : File Functions Much faster than system()… unlink “file”; - deletes a file rename “oldfile”, “newfile”; rmdir “directory”; link “existingfile”, “newfile”; symlink “existingfile”, “newfile”; chmod 0644, “file1”, “file2”, …; chown $uid, $gid, @filelist; Launching external program : Launching external program System – Execute $command and return to your script when finished. system($command, @arguments); # For example: system( "sh", "script.sh", "--help" ); system("sh script.sh --help"); You may check $! for certain errors passed to the OS by the external application Exec - This is very similar to the use of system, but it will terminate your script upon execution. Backticks or qx// - Execute command and return output on command line my $output = `script.sh --option`; my $output = qx/script.sh --option/; Special Variables : Special Variables $$ current process’ PID $` $’ pre-match & post-match strings $. input line number $/ input record separator (\n) $, output field separator for print $\ output record separator (none) Special Variables : Special Variables $! system error message (related to $ERRNO variable) $[ first element index number (0) $^O Operating System’s name @INC library directories (require, use) @ARGV command line args list %ENV Environment variables You do not have the permission to view this presentation. In order to view it, please contact the author of the presentation.
perl tutorial Jadav3000 Download Post to : URL : Related Presentations : Share Add to Flag Embed Email Send to Blogs and Networks Add to Channel Uploaded from authorPOINT lite Insert YouTube videos in PowerPont slides with aS Desktop Copy embed code: (To copy code, click on the text box) Embed: URL: Thumbnail: WordPress Embed Customize Embed The presentation is successfully added In Your Favorites. Views: 332 Category: Science & Tech.. License: All Rights Reserved Like it (2) Dislike it (0) Added: September 14, 2010 This Presentation is Public Favorites: 0 Presentation Description No description available. Comments Posting comment... By: jiten_nigam (20 month(s) ago) nice presentation sir..plz send it to me karannigam482@gmail.com thanks Saving..... Post Reply Close Saving..... Edit Comment Close Premium member Presentation Transcript Perl Training : Perl Training By Jadav Bheda What is Perl? : What is Perl? Practical Extraction and Report Language ‘A general-purpose programming language originally developed for text manipulation and now used for a wide range of tasks including system administration, web development, network programming, GUI development, and more.’ Slide 3: Parser Compiler Optimizer Interpreter Syntax Tree Unoptimized Bytecode Optimized Bytecode Fully-laden Interpreter Precompiled Bytecode What's Perl good/bad for? : What's Perl good/bad for? ‘Many earlier computer languages, such as Fortran and C, were designed to make efficient use of expensive computer hardware. In contrast, Perl is designed to make efficient use of expensive computer programmers. Good for: Quick scripts, complex scripts Parsing & restructuring data files CGI-BIN scripts High-level programming Networking libraries Graphics libraries Database interface libraries Bad for: Compute-intensive applications (use C) Hardware interfacing (device drivers…) Let's Code! : Let's Code! #!/usr/bin/perl -w #-w enables warning #use warnings; -- this could have used instead of -w # This is comment use strict; # perl is dynamic typed like VB my $name = ‘Vavni’; print “\n hello world from $name.\n”; Perl Datatypes : Perl Datatypes Scalar: a single piece of information. Scalars can hold numbers or text $ is the identifier of scalar in perl There are special variables for the system: $ARGV,$! List: an ordered collection of scalars @array = ( 1, 2 ) @words = ( "first", "second", "third" ) Hash: special arrays with words as index. %hash = (“key1” => val1, “key2” => val2); ** Don't forget undef Example of Scalar : Example of Scalar $num = 42 $num2 = “42” $name = ‘joe’ $color = “blue” $string_w_num = “I have 10 apples” $foo = “” $foo =‘’ Quoting and Interpolation : Quoting and Interpolation Double quote(“”), single quote('') and qq Example: my $var = 10; print “Value is : $var”; print 'Value is : $var”; print qq { Value is : $val }; Boolean : Boolean Undefined values are treated as false Scalars are evaluated as: numbers are evaluated as true if non-zero strings are evaluated as true if non-empty $var = “false”; if($var) { print “$var is true!\n”; } User Input / Command-line arg : User Input / Command-line arg Scripts can take inputs in two ways: Prompted inputs from users $user_text = <STDIN> Command-line Arguments ./print_args.pl ARG1 ARG2 $0 = program name @ARGV array of arguments to program Example yourprog -a somefile $0 is “yourprog” $ARGV[0] is “-a” $ARGV[1] is “somefile” Operators : Operators Math The usual suspects: + - * / $total = $subtotal * (1 + $tax / 100.0); Exponentiation: ** $cube = $value ** 3; $cuberoot = $value ** (1.0/3); Bit-level Operations left-shift: << $val = $bits << 1; right-shift: >> $val = $bits >> 8; Operators (cont..) : Operators (cont..) Assignments As usual: = += -= *= /= **= <<= >>= $value *= 5; $longword <<= 16; Increment: ++ $counter++ ++$counter Decrement: -- $num_tries-- --$num_tries Operators (cont..) : Operators (cont..) Boolean (against bits in each byte) Usual operators: & | Exclusive-or: ^ Bitwise Negation: ~ $picture = $backgnd & ~$mask | $image; Boolean Assignment &= |= ^= $picture &= $mask; Operators (cont..) : Operators (cont..) Logical (expressions) && And operator | | Or operator ! Not operator AND And, low precedence OR Or, low precedence NOT Not, low precedence XOR Exclusive or, low precedence open ( FILE, "<filename" ) || die ..... open FILE, "<filename" or die .... # Notice how the much lower # precedence of "or" makes the parenthesis unnecessary in this case. Operators (cont..) : Operators (cont..) Short Circuit Operators expr1 && expr2 expr1 is evaluated. expr2 is only evaluated if expr1 was true. expr1 || expr2 expr1 is evaluated. expr2 is only evaluated if expr1 was false. Examples open (…) || die “couldn’t open file”; $debug && print “user’s name is $name\n”; Operators (cont..) : Operators (cont..) Modulo: % $a = 123 % 10; ($a is 3) Multiplier: x print “ride on the ”, “choo-”x2, “train”;(prints “ride on the choo-choo-train”) $stars = “*” x 80; Assignment: %= x= String Concatenation: . .= $name = “Uncle” . $space . “Sam”; $cost = 34.99; $price = “Hope Diamond, now only \$”; $price .= “$cost”; Conditional Operators : Conditional Operators numeric string * Equal: == eq * Less/Greater Than: < > lt gt * Less/Greater or equal:<= >= le ge * Comparison: <=> cmp * Results in a value of -1, 0, or 1 * Zero and empty-string means False * All other values equate to True Control Structures : Control Structures “if” statement - first style if ($porridge_temp < 40) { print “too hot.\n”;}elsif ($porridge_temp > 150) { print “too cold.\n”;}else { print “just right\n”;} Control Structures (cont..) : Control Structures (cont..) “if” statement - second style statement if condition; print “\$index is $index” if $DEBUG; Single statements only Simple expressions only “unless” is a reverse “if” statement unless condition; print “millenium is here!” unless $year < 2000; Control Structures (cont..) : Control Structures (cont..) “for” loop - first style for (initial; condition; increment) { code } for ($i=0; $i<10; $i++) { print “hello\n”; } “for” loop - second style for [variable] (range) { code } for $name (@employees) { print “$name is an employee.\n”;} “for” loop with default loop variable for (@employees) { print “$_ is an employee\n”; print; # this prints “$_” } Control Structure (Cont..) : Control Structure (Cont..) “while” loop while (condition) { code } $cars = 7;while ($cars > 0) { print “cars left: ”, $cars--, “\n”;} “until” loop is opposite of “while” until (condition) { code } $cars = 7;until ($cars <= 0) { print “cars left: ”, $cars--, “\n”;} Control Structures (cont..) : Control Structures (cont..) Loop Controls “next” operator - go on to next iteration (as continue in C) “redo” operator - re-runs current iteration “last” operator - ends the loop immediately (as break in C) while (cond) { next if $a < 5;} Break out of multilevel loops using labels (as goto in C) top: while (condition) { for ($car in @cars) { … do stuff … next top if situation; }} List : List List (one-dimensional array) @memory = (16, 32, 48, 64); @people = (“Alice”, “Alex”, “Albert”); First element numbered 0 (can be changed) Single elements are scalar: $names[0] = “Ferd”; Slices are ranges of elements @guys = @people[1..2]; How big is my list? print “Number of people: $#people\n”; Some Useful Functions : Some Useful Functions push( ), pop( )- stack operations on lists shift( ),unshift( ) - bottom-based ops split( ) - split a string by separator @parts = split(/:/,$passwd_line); while (split) … # like: split (/\s+/, $_) splice( ) - remove/replace/sub str of array substr( ) - substrings of a string Some Useful Functions : Some Useful Functions length( ) - length in bytes (strings) stat( ) - file stats (times, sizes, ...) pack( ),unpack( ) - byte/record packing hex( ) - hex string to integer conv printf( ) - formatted printing sprintf( ) - printf into a string $str = sprintf (“expense = %.2f”, $expns); Hash : Hash Hash (associative array) %var = { “name” => “paul”, “age” => 33 }; Single elements are scalar print $var{“name”}; $var{age}++; How many elements are in my hash? @allkeys = keys(%var); $num = $#allkeys; Dealing with Hashes : Dealing with Hashes keys( ) - get an array of all keys foreach (keys (%hash)) { … } values( ) - get an array of all values @array = values (%hash); each( ) - get key/value pairs while (@pair = each(%hash)) { print “element $pair[0] has $pair[1]\n”;} Dealing with Hashes : Dealing with Hashes exists( ) - check if element exists if (exists $hash{$key}) { … } delete( ) - delete one element delete $hash{$key}; Subroutine : Subroutine Defined using the sub command: sub name { ... } Called from the main program or another subroutine using its name: name; Sometimes you will see in old Perl programs (like mine) &name; But is optional in modern Perl. Subroutine (cont..) : Subroutine (cont..) Subroutines can be placed anywhere in the program but best to group them at the end; # main program . . exit; # subroutines defined here sub sub1 { ... } sub sub2 { ... } sub sub3 { ... } Slide 31: All the parameters in a Perl subroutine (including arrays) end up in a single array called @_ Therefore in the code: By default the subroutine returns the last thing evaluated but you can use the return statement to make this explicit: $pos = find_motif($motif,$protein); . sub find_motif { $a = $_[0]; $b = $_[1]; ...return $b; } Subroutine (cont..) : Subroutine (cont..) What if want to pass two arrays to subroutine?(As everything arrives in the sub in a single array) $seq=compare_seqs(@seqs1,@seqs2); Solution: Use references (pointers) References (sometimes called pointers in other languages) can be more convenient because in Perl they are scalars → often much smaller than the object they refer to (e.g. an array or hash). Array references can be passed around and copied very efficiently, often also using less memory. Being scalars, they can be used to make complicated data structures such as arrays of arrays, arrays of hashes and so on.. Subroutine (cont..) : Subroutine (cont..) Simplest way to create a reference in Perl is with \ To get back the original object the reference needs to be dereferenced; $scalar_ref = \$sequence; # reference to a scalar $dna_ref = \@DNA_list; # reference to an array $hash_ref = \%genetic_code; # reference to a hash $scalar = $$scalar_ref; # for scalars just add $ @new_dna = @$dna_ref; # for arrays just add @ %codon_lookup = %$hash_ref; # similary for hashes Subroutine (cont.. ) : Subroutine (cont.. ) Solution to two array problem # compare two databases, each held as an array # $results = compare_dbase(\@dbase1,\@dbase2); # supply refs ... sub compare_dbase { my ($db1_ref,$db2_ref) = @_; # params are refs to arrays @db1 = @$db1_ref; # dereference @db2 = @$db2_ref; # dereference ... # now use @db1,@db2 return $results; } Variable Scope : Variable Scope Perl has two types of scope Package scope Package scope is default scope Global scope; exist through out program life Use 'our' for strict definition Local scope (my, local) Use 'my' to declare local variables my $var=5; My ($one, $two, @three) = (1, 2, @_); Local is temporary global (it's history) http://perl.plover.com/FAQs/Namespaces.html#Package_Variables Slide 36: My Vs Local $lo = 'global'; $m = 'global'; A(); sub A { local $lo = 'AAA'; my $m = 'AAA'; B(); } sub B { print "B ", ($lo eq 'AAA' ? 'can' : 'cannot')," see the value of lo set by A.\n"; print "B ", ($m eq 'AAA' ? 'can' : 'cannot')," see the value of m set by A.\n"; } This prints B can see the value of lo set by A. B cannot see the value of m set by A. Local static (as in C) : Local static (as in C) Local static implementation in perl: { my $seed = 1; sub my_rand { $seed = int(($seed * 1103515245 + 12345) / 65536) % 32768; return $seed; } } $seed will be created only a first time when outer block executes, not every time when my_rand subroutine executes. Basic File I/O : Basic File I/O Reading a File open (FILEHANDLE, “$filename”) or die “Reading of file $filename failed: $!”;while (<FILEHANDLE>) { chomp $_; # or just: chomp; print “$_\n”;}close FILEHANDLE; Basic File I/O : Basic File I/O Writing a File open (FILEHANDLE, “>$filename”) or die “Writing to file $filename failed: $!”;while (@data) { print FILEHANDLE “$_\n”; # note, no comma!}close FILEHANDLE; Basic File I/O : Basic File I/O Predefined File Handles <STDIN> input <STDOUT> output <STDERR> output print STDERR “big bad error occurred\n”; <> ARGV or STDIN Basic File I/O : Basic File I/O How does <> work? opens each ARGV filename for reading if no ARGV’s, reads from stdin great for writing filters, here’s “cat”: while (<>) { print; # same as print “$_”;} File Test Operators : File Test Operators Existence: if (-e “file”) Readable, Writable, Executable: -r -w -x Zero size file, non-zero size file: -z -s Plain File, Directory, Symlink: -f -d -l Named Pipe, Socket: -p -S TTY attached: -t if (-t STDIN) # is stdin a terminal or not? File Functions : File Functions Much faster than system()… unlink “file”; - deletes a file rename “oldfile”, “newfile”; rmdir “directory”; link “existingfile”, “newfile”; symlink “existingfile”, “newfile”; chmod 0644, “file1”, “file2”, …; chown $uid, $gid, @filelist; Launching external program : Launching external program System – Execute $command and return to your script when finished. system($command, @arguments); # For example: system( "sh", "script.sh", "--help" ); system("sh script.sh --help"); You may check $! for certain errors passed to the OS by the external application Exec - This is very similar to the use of system, but it will terminate your script upon execution. Backticks or qx// - Execute command and return output on command line my $output = `script.sh --option`; my $output = qx/script.sh --option/; Special Variables : Special Variables $$ current process’ PID $` $’ pre-match & post-match strings $. input line number $/ input record separator (\n) $, output field separator for print $\ output record separator (none) Special Variables : Special Variables $! system error message (related to $ERRNO variable) $[ first element index number (0) $^O Operating System’s name @INC library directories (require, use) @ARGV command line args list %ENV Environment variables