Tutorial perl programming basic eng ver


Published on

Tutorial perl programming basic english Version

Published in: Education, Technology
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Tutorial perl programming basic eng ver

  1. 1. By : Qrembiezs I
  2. 2. A Basic ProgramExample :#!/usr/local/bin/perl## Program to do the obvious#print Hello world.; # Print a messageExplaination :1st Line In the Perl language all began with this#!/usr/local/bin/perl although this may vary from system to system. This line tells the machine what to do with the file when runComments and statementsComments can be entered into the program with the symbol # and the other was ignored except for the first row only wayto stretch the comments of some of the lines is to use the # on each line Everything else is a Perl statement which mustend with a semicolon, such as the last line above.Simple printingPrint function outputs some information. In the above case it prints out a literal string Hello world. and of course end with astatement koma.Qta can find the above program produces an slightly unexpected result. So, the next thing to do is to run. Running The ProgramType in the example program using a text editor and save it. Emacs is a good editor to use because it has its own Perl modewhich formats a good line when you hit tab (use `Mx perl-mode ). But as always, use whichever you are most comfortable.Having been enter and save the program, make sure the file is executable by using the commandchmod u+x prognameat the UNIX prompt, where progname is the name of the program file. Now to run the program just type any of the followingat the prompt.
  3. 3. perl progname./prognameprognameIf something goes wrong then we can get the error message, or you might get something. We can always run this programwithout any warning using the commandperl -w prognameat the prompt. This will display a warning and the other (hopefully) helpful messages before trying to run the program. Torun the program with a debugger use the commandperl -d prognameWhen the file is executed Perl first compiles and then runs the compiled version. So after a short pause for compilation theprogram should run quite fast. This also explains why we can get a compilation error when we execute a Perl file whichconsists only of text.Make sure your program works before proceeding. Program output may be slightly unexpected - at least not very pretty.We will see next in the variable and then tie it by printing more beautiful. Scalar VariableThe most basic type of variable in Perl is a scalar variable. Scalar variables hold both strings and numbers, and areremarkable in the string and the numbers actually interchangeable. as an example,$priority = 9;sets the scalar variable $ priority to 9, but you can also specify a string to the exact same variables:$priority = high;Perl also accepts numbers as strings, like this:$priority = 9;$default = 0009;and can still cope with arithmetic and other operations. In general variable names consists of numbers, letters andunderscores, but they do not have to start with the numbers and the variable $ _ is special, as we shall see later. Also, Perlis case sensitive, so $ a and $ A are different.
  4. 4. Operation And AssignmentPerl uses all C arithmetic operators:$a = 1 + 2; # Add 1 and 2 and store in $a$a = 3 - 4; # Subtract 4 from 3 and store in $a$a = 5 * 6; # Multiply 5 and 6$a = 7 / 8; # Divide 7 by 8 to give 0.875$a = 9 ** 10; # Nine to the power of 10$a = 5 % 2; # Remainder of 5 divided by 2++$a; # Increment $a and then return it$a++; # Return $a and then increment it--$a; # Decrement $a and then return it$a--; # Return $a and then decrement itAnd for a string of Perl is like this$a = $b . $c; # Concatenate $b and $c$a = $b x $c; # $b repeated $c timesTo assign values Perl$a = $b; # Assign $b to $a$a += $b; # Add $b to $a$a -= $b; # Subtract $b from $a$a .= $b; # Append $b onto $aNote that when Perl provides the value with $ a = $ b it makes a copy of $ b and then assign that to $ a. Therefore the nexttime you change $ b it will not alter $ a.Other operators can be found on pages furlough. Men leave the prompt type.InterpolationThe following code prints using the concatenation:$a = apples;$b = pears;print $a. and .$b;It would be better to include only one string in the final printed report, but the lineprint $a and $b;prints literally $ a and $ b are not very helpful. Instead, we can use double quotes in single quotes:print "$a and $b";
  5. 5. Double quotes force interpolation of any codes, including interpreting variables. It is much nicer than our originalstatement. Another code that interpolated include special characters such as newline and tab. Code n is newline and tis tab.ExerciseThis exercise is to rewrite the Hello world program so that (a) string is assigned to a variable and (b) the variable is thenprinted with a newline character. Use double quotes and do not use the concatenation operator .. Array Variablesarray variable is a list of scalar (ie numbers and strings). Array variables have the same format as scalar variables exceptthat they are preceded by the @ symbol.statement :@food = ("apples", "pears", "eels");@music = ("whistle", "flute");provide a list of three elements in the array variable @ food and two lists of elements in the array variable @ music. Arrayis accessed by using indices starting from 0, and square brackets are used to determine the index.$food[2]Note that the @ has changed to $ for scalarArray assignmentsin all of Perl, the same expressions in different contexts can produce different results. The first assignment below explodesthe @ music variable so that the equivalent of the second task.@moremusic = ("organ", @music, "harp");@moremusic = ("organ", "whistle", "flute", "harp");This should suggest a way of adding elements to the array. Neater way of adding elements is to use the statementpush(@food, "eggs");eggs are pushed to the end of the array @ food. To encourage two or more items to one of the use of arrays in thefollowing forms:push(@food, "eggs", "lard");push(@food, ("eggs", "lard"));push(@food, @morefood);
  6. 6. Function returns a long encouraged a new list. To remove the last item from the list and return it using the pop function.From our original list the pop function returns eels and @ food now has two elements:$grub = pop(@food); # Now $grub = "eels"It is also possible to assign an array to a scalar variable. As usual context is important.$f = @food;provide long @ food, but$f = "@food";transform a list into a string with a space between each element. This space can be replaced by any other string bychanging the value of the variable $ special ". Variable is just one of many special Perl variable, most of which have strangenames.Arrays can also be used to create multiple tasks to scalar variables:($a, $b) = ($c, $d); # Same as $a=$c; $b=$d;($a, $b) = @food; # $a and $b are the first two # items of @food.($a, @somefood) = @food; # $a is the first item of @food # @somefood is a list of the # others.(@somefood, $a) = @food; # @somefood is @food and # $a is undefined.because arrays are greedy, and @ @ somefood will eat as much food. Therefore should be avoided.You may want to look for an index of the last element of the list. To do this for the @ food array use the expression$#foodDisplaying ArraysBecause context is so important, not surprisingly, has a lot of procedure with varying resultsprint @food; # By itselfprint "@food"; # Embedded in double quotesprint @food.""; # In a scalar context
  7. 7. File HandlingHere is the basic perl program that is not the same as the UNIX cat command on a particular file.#!/usr/local/bin/perl## Program to open the password file, read it in,# print it, and close it again.$file = /etc/passwd; # Name the fileopen(INFO, $file); # Open the file@lines = <INFO>; # Read it into an arrayclose(INFO); # Close the fileprint @lines; # Print the arrayOpen function opens the file for input (ie for reading). The first parameter is the filehandle which allows Perl to refer to afile in the future. The second parameter is an expression that shows the name of the file. If the given file name in quotes istaken literally without shell expansion. So the expression ~ / notes / todolist will not be interpreted successfully. If youwant to force shell expansion then use angled brackets: that is, use <~ / notes / todolist> instead.Close function tells Perl to finish with the file. There are some useful points to add to this discussion filehandling. First, openstatement can also specify a file for output and to add and feedback. To do this, prefix the name with the file> and >> foroutput to add:open(INFO, $file); # Open for inputopen(INFO, ">$file"); # Open for outputopen(INFO, ">>$file"); # Open for appendingopen(INFO, "<$file"); # Also open for inputSecondly, if you want to print something to the file you have opened for output then you can use the print statement with anadditional parameter. To print a string to a file using the filehandle INFOprint INFO "This line goes to the file.n";When, you can use the following to open the standard input (usually keyboard) and standard output (usually the screen)respectively:open(INFO, -); # Open standard inputopen(INFO, >-); # Open standard outputIn the above program information is read from the file. File is the INFO file and to read from it Perl uses angled brackets. Sothe statement@lines = <INFO>;
  8. 8. read the file denoted by the filehandle into the array @ lines. Note that the expression <INFO> read the whole file. This isbecause reading occurs in the context of an array variable. If @ lines is replaced by the scalar $ Lines is just one the nextline will be read in. In either case each line is stored complete with its newline character at the end. Control StructurePerl supports many different types of control structures which tend to be like in C, but very similar to Pascal, too. Here wediscuss some of them.ForeachTo go through every line of the array or list-like structures (such as lines in a file) Perl uses the foreach structure.foreach $morsel (@food) # Visit each item in turn # and call it $morsel{ print "$morseln"; # Print the item print "Yum yumn"; # That was nice}Actions to be performed each time a block enclosed in curly braces. The first time through the block $ morsel set the valueof the first item in the array @ food. This time it was given the value of the second item, and so on until the end. If @ food isempty to start with the block of statements is never executed.TestingThe next few structures rely on a test being true or false. In Perl any non-zero number and non-empty string is counted astrue. The number zero, zero by itself in a string, and the empty string are counted as false. Here are some tests onnumbers and strings.$a == $b # Is $a numerically equal to $b? # Beware: Dont use the = operator.$a != $b # Is $a numerically unequal to $b?$a eq $b # Is $a string-equal to $b?$a ne $b # Is $a string-unequal to $b?You can also use logical and, or and not($a && $b) # Is $a and $b true?($a || $b) # Is either $a or $b true?!($a) # is $a false?
  9. 9. ForPerl has a for structure that mimics C.for (initialise; test; inc){ first_action; second_action; etc}First of all the statement initialise to dijalankan.Then action block is executed. After each block implemented inc occurred.Here is an example for loop to print the numbers 0 through 9.for ($i = 0; $i < 10; ++$i) # Start with $i = 1 # Do it while $i < 10 # Increment $i before repeating{ print "$in";}While And UntilThe following is a program that reads some input from the keyboard and will not continue until it is the correct password#!/usr/local/bin/perlprint "Password? "; # Ask for input$a = <STDIN>; # Get inputchop $a; # Remove the newline at endwhile ($a ne "fred") # While input is wrong...{ print "sorry. Again? "; # Ask again $a = <STDIN>; # Get input again chop $a; # Chop off newline again}code is executed while the input is not the same as the password. Temporary structures should be fairly obvious, but this isan opportunity to see some things. First, we can we read from standard input (keyboard) without opening the file first.Second, when the password entered $ a given value including the newline character at the end. Function of cut to removethe last character of the string which in this case is a new line.To test this we could otherwise use to claim in just the same way. It executes the block repeatedly until the expressionevaluates to true.Are useful while others are placed or until check at the end than at the beginning of the block statement. This would requirethe presence of the operator to mark the beginning of the block and the test at the end. Once again the message in theabove password program then it can be written like this.
  10. 10. #!/usr/local/bin/perldo{ "Password? "; # Ask for input $a = <STDIN>; # Get input chop $a; # Chop off newline}while ($a ne "fred") # Redo while wrong input ConditionalsOf course Perl also allows if / then / else statements.if ($a){ print "The string is not emptyn";}else{ print "The string is emptyn";}For this, remember that an empty string is considered false. It will also provide "empty" occur if $ a is string 0.Hal is alsopossible to include more alternatives in a conditional statement:if (!$a) # The ! is the not operator{ print "The string is emptyn";}elsif (length($a) == 1) # If above fails, try this{ print "The string has one charactern";}elsif (length($a) == 2) # If that fails, try this{ print "The string has two charactersn";}else # Now, everything has failed{ print "The string has lots of charactersn";}In this case, it is important to note that the else if statement really has the "e" is missing.
  11. 11. String MatchingOne of the most useful features of Perl (if not the most useful feature) is its powerful string manipulation facilities. At theheart of this is the regular expression (RE) which is shared by many other UNIX utilities.Reguler ExpressionRegular expression is contained in slashes, and matching occurs with the operator ~ =. The following expression is true ifthe string appears in the variable $ setence.$sentence =~ /the/RE is case sensitive, so$sentence = "The quick brown fox";Make false match going on. Operator! ~ Is used for spotting Non Match. In the example above$sentence !~ /the/true because the string does not appear in $ sentenceThe $_ special variableThis time we will use as a Conditionalif ($sentence =~ /under/){ print "Were talking about rugbyn";}It will print a message if we insert the following code$sentence = "Up and under";$sentence = "Best winkles in Sunderland";But it would be easier if we give the sentence in a special variable $ which, of course scalar. If we do this then we can avoidusing the match and non-match operators and above can be written simply asif (/under/){ print "Were talking about rugbyn";}$ Variable is the default form for the operation of Perl, a lot and tend to be used
  12. 12. More on REsIn an RE there are plenty of special characters, and this is good to give them power and makes them look very complicated.Best to establish the use of REs slowly; their creation can be something of an art form.Here are some special characters and their meanings Re. # Any single character except a newline^ # The beginning of the line or string$ # The end of the line or string* # Zero or more of the last character+ # One or more of the last character? # Zero or one of the last characterand here is an example of some of the matching. Remember that should be included in slashes / ... / to be used.t.e # t followed by anthing followed by e # This will match the # tre # tle # but not te # tale^f # f at the beginning of a line^ftp # ftp at the beginning of a linee$ # e at the end of a linetle$ # tle at the end of a lineund* # un followed by zero or more d characters # This will match un # und # undd # unddd (etc).* # Any string without a newline. This is because # the . matches anything except a newline and # the * means zero or more of these.^$ # A line with nothing in it.There are more choices. Square brackets are used to match any one character in it. Inside the square brackets - shows"between" and a ^ at the beginning means "not":[qjk] # Either q or j or k[^qjk] # Neither q nor j nor k[a-z] # Anything from a to z inclusive[^a-z] # No lower case letters[a-zA-Z] # Any letter[a-z]+ # Any non-zero sequence of lower case lettersAt this point you may be able to skip to the end and do at least most of the exercises. The rest is mostly just for reference.
  13. 13. A vertical bar | is "or" and parentheses (...) can be used to group things together:jelly|cream # Either jelly or cream(eg|le)gs # Either eggs or legs(da)+ # Either da or dada or dadada or...And this is a special form of its charn # A newlinet # A tabw # Any alphanumeric (word) character. # The same as [a-zA-Z0-9_]W # Any non-word character. # The same as [^a-zA-Z0-9_]d # Any digit. The same as [0-9]D # Any non-digit. The same as [^0-9]s # Any whitespace character: space, # tab, newline, etcS # Any non-whitespace characterb # A word boundary, outside [] onlyB # No word boundaryClearly characters like $, |, [,), , / and so on are peculiar cases in regular expressions. If you want tmatch to any of themthen you have to precede it with a backslash. So:| # Vertical bar[ # An open square bracket) # A closing parenthesis* # An asterisk^ # A carat symbol/ # A slash # A backslashSome examples of RE[01] # Either "0" or "1"/0 # A division by zero: "/0"/ 0 # A division by zero with a space: "/ 0"/s0 # A division by zero with a whitespace: # "/ 0" where the space may be a tab etc./ *0 # A division by zero with possibly some # spaces: "/0" or "/ 0" or "/ 0" etc./s*0 # A division by zero with possibly some # whitespace./s*0.0* # As the previous one, but with decimal # point and maybe some 0s after it. Accepts # "/0." and "/0.0" and "/0.00" etc and # "/ 0." and "/ 0.0" and "/ 0.00" etc.
  14. 14. Substitution And TranslationAs well as identifying regular expressions Perl can make substitutions based on the match. The way to do this is to usefunctions designed to mimic the way substitution is done in a text editor vi. Once again the match operator is used, andonce again if omitted then the substitution is assumed to take place with $ Variable.To replace the occurrence of london by London in the string $ sentence we use the expression$sentence =~ s/london/London/and to do the same thing with the $ a variable, onlys/london/London/Note that two regular expressions (london and London) are surrounded by a total of three slashes. The results of thisexpression is the number of substitutions made, so it is either 0 (false) or 1 (true) in this case.OptionsThis example only replaces the first string, and maybe that there will be more than one such string we want to replace. Tomake a global substitution last slash is followed by ag as follows:s/london/London/gthe which of course can be used in the $ Variable. Again the expression returns the number of substitutions made, which is0 (false) or something greater than 0 (right).If we want to also replace London, London, London and so on then we can uses/[Ll][Oo][Nn][Dd][Oo][Nn]/London/gbut an easier way is to use the i option (for "ignore"). Expressions/london/London/giwill make a global substitution ignoring case. I also used the option in the / ... / regular expression match.
  15. 15. Remembering PaternsIts often useful to remember patterns that have been matched so that they can be used again. It just so happens thatanything matched in parentheses will be remembered in the variable $ 1, ..., $ 9. This string can also be used in the sameregular expression (or substitution) using the special RE codes 1, ..., 9. for example$_ = "Lord Whopper of Fibbing";s/([A-Z])/:1:/g;print "$_n";will replace each upper case letter by letter surrounded by colons. This will print: L: ord: W: hopper of: F: ibbing. Variablevariables $ 1, ..., $ 9 are read-onlyAnother example of hisif (/(b.+b) 1/){ print "Found $1 repeatedn";}will identify repeated words. Each b represents a word boundary and + matches any string that is not empty., So b. + B matches anything between two word boundaries. Is then remembered by the parentheses and stored as 1 for regularexpressions and as $ 1 for the entire program.The following swaps the first and last character of the line in the variables/^(.)(.*)(.)$/321/The ^ and $ match the beginning and end of the line. Storing code 1 character first, while the 2 code stores everythingelse up to the last character code stored in 3. Then that whole line is replaced with 1 and 3After matching, coz can use the special read-only variables $ `and $ & and $ to find what works before, during and afterthe search. So after.$_ = "Lord Whopper of Fibbing";/pp/;Finally on the subject of remembering patterns its worth knowing that in the slashes of a match or a substitution variablesare interpolated. so$search = "the";s/$search/xxx/g;will replace the xxx. If for change then we can not do s / $ searchre / xxx / because this will be interpolated as $ searchrevariable. Instead we should put the variable name in curly braces so that the code becomes$search = "the";s/${search}re/xxx/;
  16. 16. SPLITA very useful function in Perl, which is divided into a string and place it into the array. Function using regular expressionsand the usual work on the $ _ variable unless otherwise specifiedSplit function is used like this:$info = "Caine:Michael:Actor:14, Leafy Drive";@personal = split(/:/, $info);Have the same overall effect, as@personal = ("Caine", "Michael", "Actor", "14, Leafy Drive");If we have information that is stored in the variable $ _ then we can only use this@personal = split(/:/);If the field is divided by the number of colons then we can use the RE codes to get the rounding code$_ = "Capes:Geoff::Shot putter:::Big Avenue";@personal = split(/:+/);It could also be like this@personal = ("Capes", "Geoff", "Shot putter", "Big Avenue");But this$_ = "Capes:Geoff::Shot putter:::Big Avenue";@personal = split(/:/);Would be like this@personal = ("Capes", "Geoff", "", "Shot putter", "", "", "Big Avenue");A word can be divided into a character, a sentence split into words and paragraphs are divided into sentences:@chars = split(//, $word);@words = split(/ /, $sentence);@sentences = split(/./, $paragraph);In the first case the null string matched between each character, and that is why the @ character array is an array ofcharacters - that is an array of strings of length 1.
  17. 17. Associative ArraysList of regular arrays allows us to access their element by number. The first element of array @ food is $ food [0]. Thesecond element is $ food [1], and so on. But Perl also allows us to create arrays that are accessed by string. This is calledan associative array.To define an associative array we use the usual parenthesis notation, but the array itself is preceded by a%. Suppose wewant to create an array of people and their ages. It will look like this:%ages = ("Michael Caine", 39, "Dirty Den", 34, "Angie", 27, "Willy", "21 in dog years", "The Queen Mother", 108);Now we can find a persons age by the following expression$ages{"Michael Caine"}; # Returns 39$ages{"Dirty Den"}; # Returns 34$ages{"Angie"}; # Returns 27$ages{"Willy"}; # Returns "21 in dog years"$ages{"The Queen Mother"}; # Returns 108Note that each list as an array of sign% has turned into a $ to access a particular element as a scalar element. Unlike listarrays the index (in this case the name of the person) is enclosed in curly braces, the idea that associative arrays arebetter than the array list.Associative arrays can be converted back into an array list simply by assigning to a list array variable. A list array can beconverted into an associative array by assigning to an associative array of variables. Ideally the list array will have an evennumber of elements:@info = %ages; # @info is a list array. It # now has 10 elements$info[5]; # Returns the value 27 from # the list array @info%moreages = @info; # %moreages is an associative # array. It is the same as %ages
  18. 18. OperatorAssociative array element does not have to (they are like hash tables) but is it possible to access all the elements in turnusing the function keys and function values:foreach $person (keys %ages){ print "I know the age of $personn";}foreach $age (values %ages){ print "Somebody is $agen";}When keys is called it returns a list of keys (indexes) of the associative array. When the values are called returns a list ofthe values of the array. These functions return a list of them in the same order, but this order has nothing to do with theorder of elements has dimasukkan.Ketika keys and values are called in scalar context they return the number of key / valuepairs in an associative array.There is also every function that returns a list of two key elements and values. Every time each is called to restore anotherkey / value pairs:while (($person, $age) = each(%ages)){ print "$person is $agen";}
  19. 19. SubroutinesLanguage Perl program allows users to define their own functions, called subroutines. They may be placed anywhere inyour program, but it may be better to put them all in the beginning or all at the end.sub mysubroutine{ print "Not a very interesting routinen"; print "This does the same thing every timen";}regardless of any parameter that may be passed. All of this will work for calling subroutines. Note that the subroutinescalled by the & character in front of the name:&mysubroutine; # Call the subroutine&mysubroutine($_); # Call it with a parameter&mysubroutine(1+2, $_); # Call it with two parametersParametersIn the case of the above parameters are accepted but ignored. When subroutines called any parameters are passed as alist in a special register array variable @ _. This variable is absolutely nothing to do with the scalar variable $ _. Thefollowing subroutines disebu just print the list. This was followed by several examples of its use.sub printargs{ print "@_n";}&printargs("perly", "king"); # Example prints "perly king"&printargs("frog", "and", "toad"); # Prints "frog and toad"Just like every other list array the individual elements of @ _ can be accessed with the square bracket notationsub printfirsttwo{ print "Your first argument was $_[0]n"; print "and $_[1] was your secondn";}Once again it must be emphasized that the index scalars $ _ [0] and $ _ [1] and so have been there with the scalar $ _which can also be used without fear of crash.
  20. 20. Returning ValuesSubroutines are always evaluated at the end. These subroutines return a maximum of two input parameters. An example ofits use follows.sub maximum{ if ($_[0] > $_[1]) { $_[0]; } else { $_[1]; }}$biggest = &maximum(37, 24); # Now $biggest is 37The & printfirsttwo above subroutines also return a value, in this one. This is because the last thing s subroutines to do isprint statement and the results of a successful print statement is always 1.Local VariableLocal Variable subroutines, and so of course are $ _ [0], $ _ [1], $ _ [2], and so on. Other variables can be made locally aswell, and is useful if we want to start changing the input parameters. The following subroutines test to see if there is onestring within another.sub inside{ local($a, $b); # Make local variables ($a, $b) = ($_[0], $_[1]); # Assign values $a =~ s/ //g; # Strip spaces from $b =~ s/ //g; # local variables ($a =~ /$b/ || $b =~ /$a/); # Is $b inside $a # or $a inside $b?}&inside("lemon", "dole money"); # trueIn fact, even be smoothed by replacing the first two lines withlocal($a, $b) = ($_[0], $_[1]);
  21. 21. Tutorial Bahasa Programm Perl Full Part Thanx’s to : Whitehat Wenkhairu Cyberheb Scifix Prabujoyoboyo Darkslayers Shamus ./Blacknotes