Sie sind auf Seite 1von 22

Agenda

Basic Perl Fundamentals

Reference: teach_yourself_perl_in_21_days.pdf

Chapter 2: Operators and Control flow


Print statements. Scalar variable: - Treat as any data type. - Declaration and Assignment ($var = value). Standard input: - Take input from user. - $input = <STDIN>; Chop Library function: - Removes trailing new line character from line. - Declaration (chop($input)). Expressions(*, +, -, /): - Applicable to scalar variables except string If (condition) { } else { }. If (cond) { } elsif (cond) { } else { } Conditional operators: (condition ? Value1 : value2) Testing equality operator(==, !=). - It used in if else, while, until loop. While loop, until loop.

Chapter 3: Understanding Scalar Values


Integer values: $variable = 1355. $variable = 01355, 0 leading treat as octal value. $variable = 1e+2. Float point value: $variable = 1.434, point value treat as float value. Hex and Octal notation: $variable = 047, 0 leading treat as octal value $variable = 0xa3, 0x leading says its hex value. Using double-quote string: \U (Uppercase), \L (Lowercase), \t (Tab), \n (New line), \E (End of). $var1 = 11, $var2 = The text \Ucontains\E the $var1; $var2 becomes The text CONTAINS the 11. $var1 = 42, $var2 = 29, $result = $var1 + $var2, $result = 71.

Operators: Exponential: $var = $a ** $b, Treat as a power of b. Remainder: $var = $a % $b, It assigns remainder of a/b to $var. Comparison: $var = $a == $b, It assigns 1 to $var if $a equal $b. >(gt), <(lt), <=(le), >=(ge), !=(ne), ==(eq) operators are used. Logical: ||(or), &&(and), !(not), xor. Bitwise: &(AND), |(OR), ^(XOR), ~(NOT), <<(Left shift), >> (Right shift). Assignment: =, +=, -=, *=, /=, %=, **=, &= String concatenation and repetition: Concatenation: $str1 = ab, $str2 = cd, $res = $str1 . $str2, $res = abcd. Repetition: $str1 = a x 5, $str1 becomes aaaaa, Conditional operator and left side assignment: $result = ($var1 == 1) ? $str1 : $str2 . $var1 == 1 ? $str1 : $str2 = Hello.

Chapter 4: More operators

Chapter 5: Lists and Array variable


Scalar variable and List: List is collection of number of scalar variables. List declaration: (17, str1, 2 << 1, $value). List range: (1..80), List contains value 1 to 80. Array: List can be stored in called Array. Array declaration: @array_name = (17, str1, 2 << 1, $value). Each element of the array is treated as a scalar variable. $scalar = $array_name[0] ; $scalar contains 17. We cant access array element by @array_name[0]. @new_array = @array_name. We can use @new = (1, 2, @array_name, 90). @new = (1, 2, 17, str1, 4, 10, 90). Length of array: $variable = @array_name. Reading array from <STDIN>. Array library functions: sort(@array_name), reverse(@array_name)

List operations: @array = (this, is, a, string); $string = join (::, @array); $string = this::is::a::string. @array = split(/::/, $string); @array = (this, is, a, string);

Chapter 6: Reading from and Writing to files


Opening a file: open (FILE_R, readfile), If file successfully opened, returns 1. open (FILE_W, >writefile), opened in write mode. open (FILE_A, >>appendfile), opened in append mode. FILE_R/W/A indicates the opened file handle. We can read line by line using $line = <FILE_HANDLE>, it reads first line. $line contains the first line content of the file. We can move to second line by $line = <FILE_HANDLE> and so on. If file is not opened, we can call die $string\n; to exit from program. We can write one file to another and also append it. $line = <FILE_R>; # $line contains first line of readfile. printf FILE_W $line; It writes the first line of the readfile to writefile. printf FILE_A $line; It appends the first line of readfile to appendfile. Append process start at the end of the append file and start appending. Closing a file: close (FILE_HANDLE);

File-Test Operator: If (-X string) where -X: -d checks, Is string directory ? -e checks, Does string name is exist ? -r checks, Is string named file readable ? -w checks, Is string named file writable ? -x checks, Is string named file executable ? -z checks, Is string named file empty ? -s checks the size of the file.

Chapter 7: Pattern Matching


Match Operator: $res = $string =~ /abc/i. It searches the abc or ABC in $string, if pattern found, non-zero assign to $res otherwise 0. i indicates case insensitivity. $res = $string !~ /abc/i. It returns true if $string has no pattern abc. If $string = asdAbcmn; First statement true and second is false. $string =~ /[a-z0-9]/ ; It searches the a-z or 0-9. $string =~ /abc|def/. It searches for pattern abc or def. To search special character use $string =~ /\*\*\*/; it search pattern ***. $string = This is string; @words = split (/ +/, $string); @words = (This, is, string). It splits $string into words by the spaces. $string = Out of the office; @words = split (/the/, $string); @words = (Out of, office); It splits the $string from where the found. Substitution Operator: $string = Abcdefgh; $string =~ s/efgh/XYZ/g; It searches pattern efgh from $string and substitute it by XYZ. $string becomes AbcdXYZ. $string =~ s/(\w+)(\d+)(\s+)/$3$2$1/ego. Translation Operator: $string = Abcdefgh, $string =~ tr/efgh/XYZ/, Here searched pattern efgh is of 4 characters and replace pattern XYZ is of 3 characters. Final $string = AbcdXYZZ.

Chapter 8: More Control Structures

For loop: Syntax example: for ($i=0; $i<value; $i++) { expression } This loop will execute expression for value times. Foreach loop: Syntax example: foreach $i (@array) { expression } Each element of the @array will assign to $i and execute expression for each element of the @array. Do statement: Syntax example: do {exp} while_or_until (cond) It executes the expression till condition in while or until loop goes wrong. Last statement: Syntax: last if (cond) ; Execution comes out from while/until/for/do loop if condition true. Next statement: Syntax: next if (cond); Execution goes to next iteration of while/until/for/do loop if condition true.

Continue Block: Syntax: continue { expression }


Expression executes at the end of each iteration of the while loop.

Goto statement: Syntax: label: statements. goto label;

Execution thread jump to label where it find. Label can be any name.

Chapter 9: Using Subroutines


Subroutine is simple like a functions and tasks. Keyword sub indicates subroutine. Syntax: sub sub_name() { execution blocks }.. It called by &sub_name(). It can return any variable value. sub sub_name {blocks.. $var_name = ret_value }. sub_name returns the ret_value through variable $var_name. We can call this subroutine by $other_var = &sub_name(). Variable $other_var contains the value of ret_value through returning by subroutine. Other way to return subroutine by return statement. local & my statements: These two statements are used to declare variables as a local to that subroutine only. Syntax: sub sub_name { local $var1; my $var2; }. $var1 is local to this subroutine and any other subroutine called by this subroutine. $var2 is local to this subroutine only. Passing values to subroutine: We can pass the values to subroutine like &sub_name ($var1, $var2, $var3). Here, three passed arguments are stored inside array @_ in order they are passed. We can use these stored arguments in subroutine by sub sub_name { @local_array = @_ ;}. Subroutine arguments can be anything like array, variable, string, etc. Subroutine can be called from other subroutine. Recursive calling subroutine is also available. BEGIN, END & AUTOLOAD: These are pre-defined subroutines. BEGIN called at the starting of the program running. END called at the end of program. AUTOLOAD is automatic called when undefined subroutine is called.

Chapter 10: Associative Array


The main difference between Associative array and ordinary array is associative array subscript can be any scalar value. Syntax: %asso_array = (sub1, 1, sub2, 2, sub3, 3). Here value 1, 2, 3 are assign to element sub1, sub2, sub3 of the associative array. Accessing: foreach $sub (key (%asso_array)) { expression }. This statement executes for each element of the %asso_array and store element in $sub variable for each execution. Adding & Deleting element: delete ($asso_array{sub1}). Deletes the sub1 from array. Remaining all the features are same as ordinary array. Only change here is accessing element is scalar value.

Chapter 11: Formatting Your Output


Print Format: Syntax example below: format MYFORMAT = =============================== Here is the text I want to display =============================== . To displays the print format, set $~ = MYFORMAT before calling write. Now, call write, it will print the format contains in MYFORMAT. If $~ is not assigned by format name then interpreter will search default format name STDOUT. That means if you have defined any format named as STDOUT then no need to assign $~ variable. We can set default format to print by select (MYFORMAT).

Chapter 12: Working With File System


Open, close, print, printf and write are the basic file system functions. Open file in read and write mode by open (READWRITE, +>filename). In-built functions: select (FILE): Set the default file, which means that calls to print, write, printf writes to default file. eof() function returns 1 when all of the input has been read. seek (FILE, dist, relative_to): dist indicates number of characters to skip, relative_to 0 indicates skipping start from beginning of the file, 1 indicates from current position and 2 indicates skip from end of the file. tell (FILE): It returns the distance in bytes between the beginning of the file to the current position. getc (FILE): Reads the character from the input file. Directory manipulation functions: mkdir (dirname): It create the new directory in current directory. chdir (dirname): It changes the directory to dirname if it exist in current directory. opendir (DIR, dirname): It opens the directory named dirname. closedir (DIR): Closes the opened directory, handled by DIR. readdir (DIR): It shows the files and directory inside directory handled DIR.

rewinddir (DIR): This function sets the current directory location to the beginning of the list of the files, which start to read again from start. rmdir (DIR): It removes the directory handled by DIR. rename (oldname, newname): This function removes the oldname file to newname. chmod (permission, filelist): This function sets the permission of files listed in argument.

Chapter 13: Process, String and Maths functions


Following system functions are used to creating processes: eval (string): This function executes the statements stored inside string. system (command): This function takes argument as a command on the shell and run it. fork (): This function creates two copies of the program, the parent process and child process. Fork returns 0 to child process and returns 1 to parent process. pipe (infile, outfile): Information sent via file outfile can be read by infile file variable. die message : This function terminates the program at the die statements. warn message : This function not terminates the program but only displays the warning massage. exit (retcode): This function exit the program with a return value code. sleep (time_val): This function suspends program for the time_val number of seconds. wait (): This function wait to complete child process. waitpid (procid, waitflag): procid is the process ID to wait for and waitflag is defined by the waitpid function.

Mathematical functions: sin ($radvalue): This function returns the sine value. cos ($radvalue): This function returns the cosine value. To convert degree value to radian: $radval = atan2 (1, 1) * $degree / 45 ; sqrt (value): This function returns the square root of value. abs (value): Returns the absolute value of the value. rand (value): Randomizes the integer between range 0 to value. srand (value): It takes the value as a random number seed.

String manipulation functions: index (string, the): It searches the from the entered string and returns the index of the starting of the searched string. rindex (string, the): It searches the starts from the right end of the string. length (string): It returns the length of the passed string. substr (expr, skipchars, length): expr contains string, skipchars is the number of character to skip from extr. Length is number of the characters after the skipchars to be returned by this function. Join and split are also string manipulation functions.

Chapter 14: Scalar conversation and List Manipulation Functions


chop (input): It removes the last new line character from the input string. chomp (input): It removes last new line character of string and returns the total number of removed characters. hex (number): Hex function assumes entered number is hexadecimal and convert it to decimal. int (floating): This function converts the floating point value to integer. oct (number): Oct function assumes the entered number is octal and convert it to decimal.

Array and List Functions: grep (pattern, list): It greps the pattern from the list. splice (array, skipelements, len, newlist): It skips the element specified by the skipelements from array and replaces the len number of elements by newlist. By the use of splice, we can replaces the list elements from array, Appending the list elements, Deleting list elements. shift (array): It removes the last element from the left, moves other elements to left and returns removed elements. push (array, elements): It adds the element to the end of list. pop (array): It removes the last element from a array and returns the removed elements. sort (array): It sorts an array elements in alphabetical order. reverse (array): It reverses the order of the list.

Chapter 17: System Variables


Refer examples of this chapter.

Thank you

Das könnte Ihnen auch gefallen