Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 109

Introduction to Perl

Theres More Than One Way to Do It


MIC Automation Club

2008 McAfee, Inc.

Agenda
Day-1  Introduction to Perl  Variables  Operators  Array and Hash Functions  Conditions and Loop Operators Day-2  Subroutines  File Operations and IO  Regular Expressions  Perl Built in functions Day-3  Test
2 2/22/2012
Confidential McAfee Internal Use Only

Programming Methodologies
Structured or Method based
C Perl

Object Oriented
C++ Perl

Event Based
C# VB

2/22/2012

Confidential McAfee Internal Use Only

What is Perl ?

What is Perl ?
Perl stands for Practical Extraction and Reporting Language. Created in 1987 by Larry Wall. Inspired from Unix like languages like Sed, Awk and Shell Script. Most Perl Modules and scripts are platform independent. C-Like syntax. Perl is a freeware and open source.

2/22/2012

Confidential McAfee Internal Use Only

Slogan!!

The Perl slogan is There's more than one way to do it

2/22/2012

Confidential McAfee Internal Use Only

How Do I Install and Run Perl?

How Do I Install and Run Perl?


Perl is available at http://www.activestate.com/Products/ActivePerl/Download.html. Command to execute a Perl program For e.g. if Helloworld.pl is a Perl script Perl Helloworld.pl

2/22/2012

Confidential McAfee Internal Use Only

Variables and Data types $scalar @array %hash

Variables
Variables are storage containers for numbers, strings, and compound structures. Perl supports three types of variables: Scalars Arrays Hashes A variable name can be up to 255 characters. A variable name cannot start with a number e.g. $64bitint (leading numbers not legal)

10

2/22/2012

Confidential McAfee Internal Use Only

Variables (contd..)
A minus sign is not legal in the variable name e.g. $file-handle (minus sign not legal) Variable name cannot have special characters other than underscore(_) e.g. $excangerateto (pound symbol not legal) Here are some valid scalar variable names: $A_Scalar_Variable $scalarNo8 $_private_scalar

11

2/22/2012

Confidential McAfee Internal Use Only

Scalars ($)

Scalars
Scalar variables store a single value. They are prefixed with a $. Consider this example: $counter $string=Hello world; $string=Hello World; $string=123; $string=123.456;

13

2/22/2012

Confidential McAfee Internal Use Only

Arrays (@)

Arrays
An array is an indexed list of values with a consistent order. Names of arrays are prefixed with @. Examples of Arrays @first_array = (1, 2, 3, 4); @second_array = ('one', '2', 'three', '4', '5');
@a = qw(fred barney betty wilma);

15

2/22/2012

Confidential McAfee Internal Use Only

Hashes (%)

Hashes
Hashes are tables of key-value pairs. They are also called associative arrays. For example: %hash = ('Mouse', 'Jerry', 'Cat', 'Tom', 'Dog', 'Spike');

17

2/22/2012

Confidential McAfee Internal Use Only

Arrays and Hash Functions

Arrays and Hash Functions

Values Grabs the values from the hash @values = values(%hash); Keys Returns a list consisting of all the keys of the named hash. @keys = keys %hash; The keys are returned in an apparently random order, but it is the same order as either the values().

19

2/22/2012

Confidential McAfee Internal Use Only

Arrays and Hash Functions


shift shift ARRAY Shifts the first value of the array off and returns it, shortening the array by 1 and moving everything down. If there are no elements in the array, returns the undefined value. push push ARRAY,LIST Treats ARRAY as a stack, and pushes the values of LIST onto the end of ARRAY. The length of ARRAY increases by the length of LIST. Returns the number of elements in the array following the completed push.

20

2/22/2012

Confidential McAfee Internal Use Only

Arrays and Hash Functions


pop ARRAY Pops and returns the last value of the array, shortening the array by one element. If there are no elements in the array, returns the undefined value .

21

2/22/2012

Confidential McAfee Internal Use Only

Arrays and Hash Functions

delete

delete LIST Deletes the specified keys and associated values from a hash, or the specified elements from an array. The operation works on individual elements or slices. For example: delete $array[0]; Also note that when deleting an array item, only the items value is emptied; it doesnt remove the item from the list or close the gap between the preceding and subsequent item(s).

22

2/22/2012

Confidential McAfee Internal Use Only

Arrays and Hash Functions

each

each HASH In a list context, returns a two-element list referring to the key and value for the next element of a hash, allowing you to iterate over it. In a scalar context, returns only the key for the next element in the hash. Information is returned in a random order.

23

2/22/2012

Confidential McAfee Internal Use Only

Arrays and Hash Functions

exists
exists EXPR Returns true if the specified hash key exists, regardless of the corresponding value, even if its undef. Returns in Scalar Context 0 if hash element or array index does not exist and 1 if hash element or array index exists.

24

2/22/2012

Confidential McAfee Internal Use Only

Arrays and Hash Functions

join

join EXPR, LIST Combines the elements of LIST into a single string using the value of EXPR to separate each element. It is effectively the opposite of split. Note that EXPR is only interpolate between pairs of elements in LIST; it will not be placed either before the first or after the last element in the string. To join together strings without a separator, supply an empty string rather than undef.

25

2/22/2012

Confidential McAfee Internal Use Only

Arrays and Hash Functions

reverse

reverse LIST In a list context, returns the elements of LIST in reverse order. In a scalar context, returns a concatenated string of the values of LIST, with all bytes in opposite order. Returns in Scalar Context String Returns in List Context List

26

2/22/2012

Confidential McAfee Internal Use Only

Arrays and Hash Functions

scalar

scalar EXPR Forces the evaluation of EXPR to be in scalar context, even if it would normally work in list context

27

2/22/2012

Confidential McAfee Internal Use Only

Arrays and Hash Functions

splice

splice ARRAY, OFFSET, LENGTH, LIST splice ARRAY, OFFSET, LENGTH splice ARRAY, OFFSET Removes the elements of ARRAY from the element OFFSET for LENGTH elements, replacing the elements removed with LIST, if specified. If LENGTH is omitted, removes everything from OFFSET onwards.

28

2/22/2012

Confidential McAfee Internal Use Only

List and Scalar Context


Every Perl expression is in one of two `contexts', either `list context' or `scalar context', depending on whether it is expected to produce a list or a scalar. Example of list context: ($a,$b,$c)=(1,2,3); @arr=(4,5,6); Example of scalar context: $a=@arr; $a=GetDate();

Confidential McAfee Internal Use Only

Operators

Operators
Basic arithmetic and logical operators

Assignment operator = Arithmetic operators +-*/%** Logical operators && || ! and or not Increment and decrement operators ++ -Comparison operators == != < <= > >= <=> eq ne lt le gt ge cmp

31

2/22/2012

Confidential McAfee Internal Use Only

Conditional Statements

Conditional Statements
Simple If If else Nested If else else if ladder unless

33

2/22/2012

Confidential McAfee Internal Use Only

Conditional Statements (contd..)


Simple if if (EXPRESSION) { Statements; }

34

2/22/2012

Confidential McAfee Internal Use Only

Conditional Statements (contd..)


The if-else condition if (EXPRESSION) { Statements; } else { Statements; }

35

2/22/2012

Confidential McAfee Internal Use Only

Conditional Statements (contd..)


Nested if-else condition
if (EXPRESSION)

{
if (EXPRESSION) { Statements; } else { Statements; } } else { Statements; }

36

2/22/2012

Confidential McAfee Internal Use Only

Conditional Statements (contd..)


else if ladder
if (EXPRESSION)

{
Statements; } elsif (EXPRESSION) { Statements; } elsif (EXPRESSION) { Statements; } else { Statements; }

37

2/22/2012

Confidential McAfee Internal Use Only

Conditional Statements (contd..)


Other forms of if statement BLOCK if EXPRESSION; STATEMENT if EXPRESSION; STATEMENT, STATEMENT, STATEMENT if EXPRESSION;

38

2/22/2012

Confidential McAfee Internal Use Only

Conditional Statements (contd..)


Unless statement unless(Expression) { Statements; } Unlike the if statement, the code block is executed only if the expression is false rather than true.

39

2/22/2012

Confidential McAfee Internal Use Only

Loops

Loops
While Loop while (<EXPRESSION>) { Statements; } While loop executes as long as the expression is true and once the expression is false, control exits the loop

41

2/22/2012

Confidential McAfee Internal Use Only

Loops (contd..)
Do While Loop do{ Statements; } while (expression); do- while loop executes as long as the expression is true and once the expression is false, control exits the loop. Unlike while loop, do-while loop is executed at least once irrespective of the truthness or falsity of the expression.

42

2/22/2012

Confidential McAfee Internal Use Only

Loops ( contd..)
Until Loop until (EXPRESSION) { Statements; } until loop executes as long as the value of the expression is false and exits the loop when the value becomes true.

43

2/22/2012

Confidential McAfee Internal Use Only

Loops (contd..)
For Loop Perl's for control structure is like the common for control structure you may have seen in other languages such as C. It looks like this: for (initialization; check; increment) { body; }

44

2/22/2012

Confidential McAfee Internal Use Only

Loops (contd..)
foreach Loop foreach loop is same as for loop but does not require initialization and increment as part of the declaration of the loop. @array=(1,2,3,4); foreach(@array) { print This is element $_\n; }

45

2/22/2012

Confidential McAfee Internal Use Only

Loop controls

Loop controls
The last Operator The last operator immediately ends the execution of the loop. (If you've used the "break" operator in C or a similar language, it's like that.) It's the "emergency exit" for loop blocks. Example: for ($i=0;$i<10;$i++) { print $i\n; last if ($i == 5); # the loop will exit here }

47

2/22/2012

Confidential McAfee Internal Use Only

Loop controls (contd..)


The next Operator The next control continues with the next iteration of the loop (much like the "continue" operator in C or a similar language):
Example: for($i=0;$i < 10;$i++) { if($i == 5) { next; to the } print $i\n;
}

#This will not print the value of $i and will go #next value in the loop 6

48

2/22/2012

Confidential McAfee Internal Use Only

Loop controls (contd..)


The redo Operator The third member of the loop control triad is redo. It says to go back to the top of the current loop block, without testing any conditional expression or advancing to the next iteration.
for($i=0;$i < 10;$i++) ####Redo comes here { if($i == 5) { $i++; redo; } print $i\n; }

# This will execute the loop again if $i==5.

49

2/22/2012

Confidential McAfee Internal Use Only

Subroutines

Subroutines
Defining a subroutine use the keyword sub, followed by the name of your subroutine, followed by a code block sub Hello { print Hello and Welcome to this world of Perl\n; }

51

2/22/2012

Confidential McAfee Internal Use Only

Subroutines (contd..)
Passing arguments to subroutines When arguments are passed to a subroutine they are stored in the default variable @_.
Getting the arguments directly from the @_ array sub Add { return $_[0] + $_[1]; } Saving the arguments list into another set of variables or another array sub Add { my ($num1,$num2)=@_; return $num1+$num2; }
52 2/22/2012
Confidential McAfee Internal Use Only

Subroutines (contd..)
Using the Shift operator to get the arguments. sub Add { my $num1=shift; my $num2=shift; return $num1+$num2; }

53

2/22/2012

Confidential McAfee Internal Use Only

Subroutines (contd..)
Passing Lists to Subroutines. Because the @_ variable is an array, it can be used to supply lists to a Subroutine. All three of the following are valid: @args = (2,3); mysub(1,@args); @args = (1,2,3); mysub(@args); More than one list cannot be passed to a subroutine without using References.

54

2/22/2012

Confidential McAfee Internal Use Only

Subroutines (contd..)
The fundamental rule to remember is that when passing arrays or lists to subroutines you can pass only one array or list, and it must be the last argument supplied. sub process { my ($first, $second, @rest) = @_; } If you try to extract the array as the first element, then it will immediately gobble up all of @_, even if there are arguments after the array leaving any scalar entries empty. sub process { my (@rest, $first, $second) = @_; }

55

2/22/2012

Confidential McAfee Internal Use Only

Subroutines (contd..)
Passing Hashes to Subroutines
When you supply a hash to a subroutine, the hash is automatically translated into a list of key/value pairs

For E.g. sub display_hash { my (%hash) = @_; foreach (keys %hash) { print "$_ => $hash{$_}\n"; } }

56

2/22/2012

Confidential McAfee Internal Use Only

Subroutines (contd..)
The fundamental rule to remember is that when passing hashes to subroutines you can pass only one, and it must be the last argument supplied. This will not work. sub display { my (%hash, $regex) = @_; }

57

2/22/2012

Confidential McAfee Internal Use Only

Subroutines (contd..)
Return Values
The return value of any block, including those used in subroutines, is taken as the value of the last evaluated expression. For example:

sub myfunc {
$_[0]+$_[1]; } The return value here is the result of the calculation. You can also explicitly return a value using the return keyword:

sub myfunc {
my $c=$_[0]+$_[1]; return $c; }

58

2/22/2012

Confidential McAfee Internal Use Only

Subroutines (contd..)
Return Context In order to discover the context in which a function has been called, you use the wantarray function. For E.g. sub hw { if (wantarray) { return('Hello','World',"\n"); } else { return "Hello World\n"; } }

59

2/22/2012

Confidential McAfee Internal Use Only

Subroutines (contd..)
Prototypes
A prototype definition is a parenthesized list of characters mirroring the Perl variable type syntax (that is, $, @, %, and so on). It is placed after the sub keyword and subroutine name but before anything else, be it a subroutine definition, declaration, or anonymous subroutine: sub mysub (PROTOTYPE); # subroutine declaratio sub mysub (PROTOTYPE) {...} # subroutine definition $subref = sub (PROTOTYPE) {...} # anonymous subroutine

For E.g. sub volume ($$$) { # ... as before ... }

60

2/22/2012

Confidential McAfee Internal Use Only

Subroutines (contd..)
Prototypes can decide the parameter sequence. If the function has to receive a certain type of parameter as the first one then in the prototype definition it must be prefixed with a \ (backslash)

E.g. sub Add(\@$$); indicates that the first argument must be an array or list followed by two scalars.

61

2/22/2012

Confidential McAfee Internal Use Only

Subroutines (contd..)
Prototypes can decide the mandatory and optional parameters. Mandatory and optional parameters are separated by a ; (semicolon) E.g. sub CircleArea($;$) This indicates that the function takes in two parameters, out of which one is mandatory

62

2/22/2012

Confidential McAfee Internal Use Only

Perl Modules

What are Perl Modules


Perl modules are discrete components of any Perl program. A module is distinguished by a unique Namespace Modules can be written in two formats.
Procedural Programming Object Oriented Programming

64

2/22/2012

Confidential McAfee Internal Use Only

Perl Module Structure


package <Module_Name>; #Add the required modules to be used use strict; use warnings; #Define the subroutine required sub Loop () { my $loopvalue=shift; return $loopvalue + 100; } #End the subroutine with this numerical 1;

65

2/22/2012

Confidential McAfee Internal Use Only

Calling a Perl Module


use Lib::MyMod; use strict; use warnings; MyMod::Loop(100);

66

2/22/2012

Confidential McAfee Internal Use Only

Working with Files

Working with Files


Opening a File open FILEHANDLE, EXPR A filehandle is a named internal Perl structure that associates a physical file with a name. A filehandle can be reused. It is not permanently attached to a single file, nor is it permanently related to a particular file name. The name of the filehandle and the name of the file are not related. As far as Perl is concerned, all operating systems support three basic filehandlesSTDIN, STDOUT, and STDERR

68

2/22/2012

Confidential McAfee Internal Use Only

Working with Files


Open a File in Read only Mode: open (FH,< Data.txt); open (FH,Data.txt); Open a File in Write Mode: open (FH,> Data.txt); This will Clear all the contents of a file before writing the new contents.

69

2/22/2012

Confidential McAfee Internal Use Only

Working with Files


Open a File for appending: open (FH,>> Data.txt);

Open a File in both Read and Write Mode: To open a file for both reading and writing prefix the > or < with a + sign. open(FH,+< Data.txt);

70

2/22/2012

Confidential McAfee Internal Use Only

Working with Files


Reading Files Reading in Scalar context Open (FH,Data.txt); My $Line=<FH>; Print $Line; open(FH,Data.txt) While(<FH>) { Print ; }

71

2/22/2012

Confidential McAfee Internal Use Only

Working with Files


Reading Files in List Context. When in a list context all the line from the filehandle and stored in the list. For e.g. Open(FH,Data.txt) My @Lines=<FH>; Print @Lines;

72

2/22/2012

Confidential McAfee Internal Use Only

Working with Files (contd..)


Writing to a File
Open(FH,> data.txt); Print FH This is a test\n;

Closing a FileHandle Close(FH);

73

2/22/2012

Confidential McAfee Internal Use Only

Working with Files


AutoFlush
The amount of data that is read from a file or written to a file is decided by the operating system. This is done for performance reasons and so that data is written in blocks. By default the autoflush is set to False.

Open(FH,> Data.txt); Select(FH); $|=1; Print FH This is a test for autoflush enabled\n; Alternaively the module IO::Handle can be used for this, use IO::Handle; open(DOOR,"<file.in") or die "Couldn't open file"; autoflush DOOR 1; To switch it back on again: autoflush DOOR 0;

74

2/22/2012

Confidential McAfee Internal Use Only

Working with Files (contd..)


Handling Errors while opening files
Using the keyword die

Open(FH,Data.txt) or die $!; This will exit the program if the file cannot be opened. The system error message is stored in $!. The user can also defined his own custom message when the error occurs. Open(FH,Data.txt) or die File Failed to open. Error $!;

75

2/22/2012

Confidential McAfee Internal Use Only

Working with Files (contd..)


Handling Errors while opening files Using the Keyword warn The warn keyword will also throw an error but will not quit the program, the execution will continue from there on. Eg: Open(FH,Data.txt) or warn File open error $!\n;

76

2/22/2012

Confidential McAfee Internal Use Only

Working with Files (contd..)


Reading the contents of a directory opendir(DIR,C:\\Program files); my @Contents=readdir(DIR); closedir(DIR); shift(@Contents); shift(@Contents); print @Contents; #Remove the . & .. symbols

77

2/22/2012

Confidential McAfee Internal Use Only

Working with Files (contd..)


File Test Operators Operator
-f -T -X -d -e -s -z

Description
Is it a File? Is it a text file? Is the file executable? Is the file a directory? Does the file exist? Returns the size of the file, with zero referring to an empty file. Is the file size zero?

78

2/22/2012

Confidential McAfee Internal Use Only

Regular Expressions

Regular Expressions
The regular expression, also called regex or regexp, is a syntax for expressing search patterns for finding and extracting matches within text. Regexps have a long history, and Perl s implementation. A key to writing good regular expressions is to understand the guiding principles of how the engine seeks a match. Perl s regular expression engine works on three basic principles, in this order: Eagerness: It will try to match as soon as possible. Greediness: It will try to match as much as possible. Relentlessness: It will try every possible combination before giving up.

80

2/22/2012

Confidential McAfee Internal Use Only

Regular Expressions (contd..)


Uses of Regular Expressions Pattern Matching (m//)

Pattern Substitution (s///)

Transliteration (tr///)

81

2/22/2012

Confidential McAfee Internal Use Only

Regular Expressions (contd..)


Pattern Matching The match operator, m//, is used to match a string or statement to a regular expression. For example, to match the character sequence foo against the scalar $bar, you might use a statement like this: if ($bar =~ m/foo/)

82

2/22/2012

Confidential McAfee Internal Use Only

Regular Expressions (contd..) Modifier


I m

Description
Makes the match case insensitive Specifies that if the string has newline or carriage return characters, the ^ and $ operators will now match against a newline boundary, instead of a string boundary Evaluates the expression only once Allows use of . to match a newline character Allows you to use white space in the expression for clarity Globally finds all matches

o s x g

83

2/22/2012

Confidential McAfee Internal Use Only

Regular Expressions (contd..)


Quantifiers * Match 0 or more times + Match 1 or more time ? Match 0 or 1 time {n} Match exactly n times Character Class shortcuts \d [0-9] A digit \D [^0-9] A non digit \s [\s\t\r\f] A whitespace character \S [^ \s\r\t\f] A non whitespace character \w [0-9a-zA-Z] A word character \W [^ 0-9a-zA-Z] A non word character

84

2/22/2012

Confidential McAfee Internal Use Only

Regular Expressions (contd..)


Pattern Matching in Scalar Context $true = ($foo =~ m/foo/); Will set $true to 1 if $foo matches the regex, or 0 if the match fails. Pattern Matching in list Context my ($hours, $minutes, $seconds) = $time =~ m/(\d+):(\d+):(\d+)/;

85

2/22/2012

Confidential McAfee Internal Use Only

Regular Expressions (contd..)


The $` $& and $ variables The $` variable has the string to left of the pattern match. The $& has the matched string. The $ has the string to the right of the pattern match.

86

2/22/2012

Confidential McAfee Internal Use Only

Regular Expressions (contd..)


The Substitution Operator The substitution operator, s///, is really just an extension of the match operator that allows you to replace the text matched with some new text. The basic form of the operator is s/PATTERN/REPLACEMENT/; For example, we can replace all occurrences of dog with cat using $string =~ s/dog/cat/;

87

2/22/2012

Confidential McAfee Internal Use Only

Regular Expressions (contd..)


Note that the return value from any substitution operation is the number of substitutions that took place. In a typical substitution, this will return 1 on success, and if no replacements are made, then it will return 0a false response. The problem with modifying strings in this way is that we clobber the original value of the string in each casewhich is often not the effect we want. The usual alternative is to copy the information into a variable first, and then perform the substitution on the new variable: $newstring = $string; $newstring =~ s/cat/dog/; or on a single line ($newstring = $string) =~ s/cat/dog/;

88

2/22/2012

Confidential McAfee Internal Use Only

Regular Expressions (contd..)


Transliteration or Translation (tr///) Transliteration is the process of replacing one letter with another. Like the substitution operator they can be used with any suitable delimiters, are bound to the input text with =~, have search and replace criteria, and even accept modifiers. The left-hand side of a transliteration is not a pattern but a list of characters to be transformed (that is, transliterated), and the right-hand side is the list of characters that they are transformed into. Each character on the left-hand side is converted into the corresponding character on the right, determined by their respective positions in the left and right lists.
89 2/22/2012
Confidential McAfee Internal Use Only

Regular Expressions (contd..)


Transliteration converts the letter a into the letter z, the letter b into the letter y, and the letter c into the letter x: $text =~ tr/abc/zyx/; If the replacement list is longer than the search list, then the trailing characters are ignored. If shorter, Perl repeats the final character until the replacement list is long enough: $text =~ tr/abcd/zy/; The return value from a transliteration is a count of the number of successful translations.

90

2/22/2012

Confidential McAfee Internal Use Only

Perl In Built Functions

Perl In Built Functions


1. abs abs EXPR Returns the absolute value of EXPR or $_. 2. binmode binmode FILEHANDLE. Sets the file read/write to binary mode. 3. chdir chdir EXPR Changes the current working directory to EXPR. Returns 0 on failure and 1 on success.

92

2/22/2012

Confidential McAfee Internal Use Only

Perl In Built Functions


4. chomp chomp EXPR chomp LIST chomp Removes the last character if it matches the value of $/ from EXPR, each element of LIST, or $_ if no value is specified. Returns Integer, number of bytes removed for all strings. 5. chop chop EXPR chop LIST chop Removes the last character from EXPR, each element of LIST,or $_ if no value is specified. Returns the the character removed from EXPR.

93

2/22/2012

Confidential McAfee Internal Use Only

Perl In Built Functions


6. crypt crypt EXPR,SALT Encrypts the string EXPR using the system crypt( ) function. The value of SALT is used to select an encrypted version from one of a number of variations. Note that there is no equivalent decryption function. You cannot (easily) decrypt a string that has been encrypted in this way. Its normally used one way, first to encrypt a string, and then to encrypt a password to compare against the encrypted string. If youre using it in this form, then consider supplying the encrypted password as the SALT.

94

2/22/2012

Confidential McAfee Internal Use Only

Perl In Built Functions


7. defined

defined EXPR defined


Returns true if EXPR has a value other than the undef value, or checks the value of $_ if EXPR is not specified. This can be used with many functions to detect a failure in operation, since they return undef if there was a problem. A simple Boolean test does not differentiate between false, zero, an empty string, or the string 0, which are all equally false. If EXPR is a function or function reference, then it returns true if the function has been defined. When used with entire arrays and hashes, it will not always produce intuitive results. If a hash element is specified, it returns true if the corresponding value has been defined, but does not determine whether the specified key exists in the hash

95

2/22/2012

Confidential McAfee Internal Use Only

Perl In Built Functions

8. eof
eof FILEHANDLE eof() eof Returns true if the next read on the specified FILEHANDLE will return an end-of-file condition, or if FILEHANDLE is not currently associated with an open file. If FILEHANDLE is not specified, it returns the condition for the last accessed file. In Scalar Context: undef if FILEHANDLE is not at end of file 1 if FILEHANDLE will report end of file on next read.

96

2/22/2012

Confidential McAfee Internal Use Only

Perl In Built Functions


9. eval eval EXPR Evaluates EXPR at execution time as if EXPR were a separate Perl script. This allows you to use a separate, perhaps user-supplied, piece of Perl script within your program. An eval EXPR statement is evaluated separately each time the function is called. . Any exceptions raised by the interpreter, die, or warn are contained in $@.

97

2/22/2012

Confidential McAfee Internal Use Only

Perl In Built Functions


10. exec exec EXPR LIST Executes a system command (directly, not within a shell) and never returns to the calling script. 11. exit exit EXPR Evaluates EXPR, exits the Perl interpreter, and returns the value as the exit value.Always runs all END{} blocks defined in the script (and imported packages) before exiting. If EXPR is omitted, then the interpreter exits with a value of 0. Should not be used to exit from a subroutine; use die or use return.

98

2/22/2012

Confidential McAfee Internal Use Only

Perl In Built Functions


12. gmtime gmtime EXPR gmtime Returns a list of values corresponding to the date and time as specified by EXPR, or date and time returned by the time function if EXPR is omitted, localized for the standard Greenwich mean time. The values returned are as follows: ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time); The array elements are numeric, taken from the system struct tm. The value of $mon has a range of 0..11, $wday has a range of 0..6 (SundaySaturday), and $year is returned as the number of years from 1900.

99

2/22/2012

Confidential McAfee Internal Use Only

Perl In Built Functions


13. hex hex EXPR hex Interprets EXPR as a hexadecimal string and returns the value, or converts $_ if EXPR is omitted. 14. int int EXPR int Returns the integer element of EXPR, or $_ if omitted. The int function does not do rounding. If you need to round a value up to an integer, you should use sprintf

100

2/22/2012

Confidential McAfee Internal Use Only

Perl In Built Functions


15. index index STR, SUBSTR, POSITION index STR, SUBSTR Returns the position of the first occurrence of SUBSTR in STR, starting at the beginning (starting at zero), or from POSITION if specified. Returns in Scalar Context -1 on failure Position of matching string (starting at zero for the first character). Also see rindex

101

2/22/2012

Confidential McAfee Internal Use Only

Perl In Built Functions


16. length length EXPR length Returns the length, in characters, of the value of EXPR, or $_ if not specified. Use scalar context on an array or hash if you want to determine the corresponding size.

102

2/22/2012

Confidential McAfee Internal Use Only

Perl In Built Functions


17. mkdir mkdir EXPR,MODE Makes a directory with the name and path EXPR using the mode specified by MODE,which should be supplied as an octal value for clarity. Return in Scalar Context 0 on failure 1 on success 18. ord ord EXPR ord Returns the ASCII numeric value of the character specified by EXPR, or $_ if omitted

103

2/22/2012

Confidential McAfee Internal Use Only

Perl In Built Functions


19. rand rand EXPR rand Returns a random fractional number between 0 and the positive number EXPR, or 1 if not specified. Automatically calls srand to seed the random number generator unless it has already been called. Returns in Scalar Context Floating point number.

104

2/22/2012

Confidential McAfee Internal Use Only

Perl In Built Functions


20. rmdir rmdir EXPR rmdir Deletes the directory specified by EXPR, or $_ if omitted. Only deletes the directory if the directory is empty.

105

2/22/2012

Confidential McAfee Internal Use Only

Perl In Built Functions


21. split split /PATTERN/, EXPR, LIMIT split /PATTERN/, EXPR split /PATTERN/ split Splits a string into an array of strings, returning the resultant list. By default, empty leading fields are preserved and empty trailing fields are deleted.

106

2/22/2012

Confidential McAfee Internal Use Only

Perl In Built Functions


22. system system PROGRAM, LIST system PROGRAM Executes the command specified by PROGRAM, passing LIST as arguments to the command. The script waits for execution of the child command to complete before continuing. If PROGRAM is the only argument specified, then Perl checks for any shell metacharacters and, if found, passes PROGRAM unchanged to the users default command shell.

107

2/22/2012

Confidential McAfee Internal Use Only

Perl In Built Functions


23. time time Returns the number of seconds since the epoch (00:00:00 UTC, January 1, 1970, for most systems; 00:00:00, January 1, 1904, for Mac OS). Suitable for feeding to gmtime and localtime.

108

2/22/2012

Confidential McAfee Internal Use Only

Thank You!!

You might also like