SlideShare uma empresa Scribd logo
1 de 21
Baixar para ler offline
By : Qrembiezs




      I
A Basic Program



Example :

#!/usr/local/bin/perl
#
# Program to do the obvious
#
print 'Hello world.';      # Print a message

Explaination        :

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 run

Comments and statements
Comments can be entered into the program with the symbol # and the other was ignored except for the first row only way
to stretch the comments of some of the lines is to use the # on each line Everything else is a Perl statement which must
end with a semicolon, such as the last line above.

Simple printing
Print function outputs some information. In the above case it prints out a literal string Hello world. and of course end with a
statement koma.Qta can find the above program produces an slightly unexpected result. So, the next thing to do is to run.



                                                      Running The Program

Type in the example program using a text editor and save it. Emacs is a good editor to use because it has its own Perl mode
which 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 command

chmod u+x progname

at the UNIX prompt, where progname is the name of the program file. Now to run the program just type any of the following
at the prompt.
perl progname
./progname
progname

If something goes wrong then we can get the error message, or you might get something. We can always run this program
without any warning using the command

perl -w progname

at the prompt. This will display a warning and the other (hopefully) helpful messages before trying to run the program. To
run the program with a debugger use the command

perl -d progname

When the file is executed Perl first compiles and then runs the compiled version. So after a short pause for compilation the
program should run quite fast. This also explains why we can get a compilation error when we execute a Perl file which
consists 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 Variable

The most basic type of variable in Perl is a scalar variable. Scalar variables hold both strings and numbers, and are
remarkable 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 and
underscores, but they do not have to start with the numbers and the variable $ _ is special, as we shall see later. Also, Perl
is case sensitive, so $ a and $ A are different.
Operation And Assignment
Perl 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 it

And for a string of Perl is like this

$a = $b . $c;             # Concatenate $b and $c
$a = $b x $c;             # $b repeated $c times

To 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 $a

Note that when Perl provides the value with $ a = $ b it makes a copy of $ b and then assign that to $ a. Therefore the next
time you change $ b it will not alter $ a.

Other operators can be found on pages furlough. Men leave the prompt type.

Interpolation
The 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 line

print '$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";
Double quotes force interpolation of any codes, including interpreting variables. It is much nicer than our original
statement. Another code that interpolated include special characters such as newline and tab. Code  n is newline and  t
is tab.

Exercise
This exercise is to rewrite the Hello world program so that (a) string is assigned to a variable and (b) the variable is then
printed with a newline character. Use double quotes and do not use the concatenation operator ..


                                                    Array Variables

array variable is a list of scalar (ie numbers and strings). Array variables have the same format as scalar variables except
that 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. Array
is 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 scalar

Array assignments
in all of Perl, the same expressions in different contexts can produce different results. The first assignment below explodes
the @ 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 statement

push(@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 the
following forms:

push(@food, "eggs", "lard");
push(@food, ("eggs", "lard"));
push(@food, @morefood);
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 by
changing the value of the variable $ special ". Variable is just one of many special Perl variable, most of which have strange
names.

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

$#food

Displaying Arrays
Because context is so important, not surprisingly, has a lot of procedure with varying results

print @food;    # By itself
print "@food"; # Embedded in double quotes
print @food.""; # In a scalar context
File Handling

Here 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 file
open(INFO, $file);                                 #   Open the file
@lines = <INFO>;                                   #   Read it into an array
close(INFO);                                       #   Close the file
print @lines;                                      #   Print the array


Open function opens the file for input (ie for reading). The first parameter is the filehandle which allows Perl to refer to a
file in the future. The second parameter is an expression that shows the name of the file. If the given file name in quotes is
taken literally without shell expansion. So the expression '~ / notes / todolist' will not be interpreted successfully. If you
want 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, open
statement can also specify a file for output and to add and feedback. To do this, prefix the name with the file> and >> for
output to add:
open(INFO,        $file);             #   Open    for input
open(INFO,        ">$file");          #   Open    for output
open(INFO,        ">>$file");         #   Open    for appending
open(INFO,        "<$file");          #   Also    open for input



Secondly, if you want to print something to the file you have opened for output then you can use the print statement with an
additional parameter. To print a string to a file using the filehandle INFO

print 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 input
open(INFO, '>-');                     # Open standard output

In the above program information is read from the file. File is the INFO file and to read from it Perl uses angled brackets. So
the statement

@lines = <INFO>;
read the file denoted by the filehandle into the array @ lines. Note that the expression <INFO> read the whole file. This is
because reading occurs in the context of an array variable. If @ lines is replaced by the scalar $ Lines is just one the next
line will be read in. In either case each line is stored complete with its newline character at the end.



                                                    Control Structure

Perl supports many different types of control structures which tend to be like in C, but very similar to Pascal, too. Here we
discuss some of them.

Foreach
To 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 value
of 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 is
empty to start with the block of statements is never executed.

Testing
The next few structures rely on a test being true or false. In Perl any non-zero number and non-empty string is counted as
true. The number zero, zero by itself in a string, and the empty string are counted as false. Here are some tests on
numbers and strings.

$a == $b                             #     Is $a numerically equal to $b?
                                     #     Beware: Don't 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?
For
Perl 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 Until
The following is a program that reads some input from the keyboard and will not continue until it is the correct password

#!/usr/local/bin/perl
print "Password? ";                              #   Ask for input
$a = <STDIN>;                                    #   Get input
chop $a;                                         #   Remove the newline at end
while ($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 is
an 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 remove
the 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 expression
evaluates to true.

Are useful while others are placed or until check at the end than at the beginning of the block statement. This would require
the presence of the operator to mark the beginning of the block and the test at the end. Once again the message in the
above password program then it can be written like this.
#!/usr/local/bin/perl
do
{
        "Password? ";                              # Ask for input
        $a = <STDIN>;                              # Get input
        chop $a;                                   # Chop off newline
}
while ($a ne "fred")                               # Redo while wrong input




                                                          Conditionals

Of 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 also
possible 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.
String Matching

One of the most useful features of Perl (if not the most useful feature) is its powerful string manipulation facilities. At the
heart of this is the regular expression (RE) which is shared by many other UNIX utilities.

Reguler Expression
Regular expression is contained in slashes, and matching occurs with the operator ~ =. The following expression is true if
the 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 $ sentence

The $_ special variable
This time we will use as a Conditional

if ($sentence =~ /under/)
{
        print "We're 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 avoid
using the match and non-match operators and above can be written simply as

if (/under/)
{
        print "We're talking about rugbyn";
}

$ Variable is the default form for the operation of Perl, a lot and tend to be used
More on REs
In 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 character



and 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 line
e$          #   e at the end of a line
tle$        #   tle at the end of a line
und*        #   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 letters



At 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.
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 char

n                       #   A newline
t                       #   A tab
w                       #   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, etc
S                       #   Any non-whitespace character
b                       #   A word boundary, outside [] only
B                       #   No word boundary

Clearly characters like $, |, [,), , / and so on are peculiar cases in regular expressions. If you want tmatch to any of them
then 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 backslash

Some 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.
Substitution And Translation

As well as identifying regular expressions Perl can make substitutions based on the match. The way to do this is to use
functions designed to mimic the way substitution is done in a text editor vi. Once again the match operator is used, and
once 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, only

s/london/London/

Note that two regular expressions (london and London) are surrounded by a total of three slashes. The results of this
expression is the number of substitutions made, so it is either 0 (false) or 1 (true) in this case.

Options
This example only replaces the first string, and maybe that there will be more than one such string we want to replace. To
make a global substitution last slash is followed by ag as follows:

s/london/London/g

the which of course can be used in the $ Variable. Again the expression returns the number of substitutions made, which is
0 (false) or something greater than 0 (right).

If we want to also replace London, London, London and so on then we can use

s/[Ll][Oo][Nn][Dd][Oo][Nn]/London/g

but an easier way is to use the i option (for "ignore"). Expression

s/london/London/gi

will make a global substitution ignoring case. I also used the option in the / ... / regular expression match.
Remembering Paterns
It's often useful to remember patterns that have been matched so that they can be used again. It just so happens that
anything matched in parentheses will be remembered in the variable $ 1, ..., $ 9. This string can also be used in the same
regular 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. Variable
variables $ 1, ..., $ 9 are read-only

Another example of his

if (/(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 regular
expressions and as $ 1 for the entire program.

The following swaps the first and last character of the line in the variable

s/^(.)(.*)(.)$/321/

The ^ and $ match the beginning and end of the line. Storing code  1 character first, while the  2 code stores everything
else up to the last character code stored in  3. Then that whole line is replaced with  1 and  3

After matching, coz can use the special read-only variables $ `and $ & and $ 'to find what works before, during and after
the search. So after.

$_ = "Lord Whopper of Fibbing";
/pp/;

Finally on the subject of remembering patterns it's worth knowing that in the slashes of a match or a substitution variables
are 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 $ searchre
variable. Instead we should put the variable name in curly braces so that the code becomes

$search = "the";
s/${search}re/xxx/;
SPLIT

A very useful function in Perl, which is divided into a string and place it into the array. Function using regular expressions
and the usual work on the $ _ variable unless otherwise specified

Split 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 of
characters - that is an array of strings of length 1.
Associative Arrays

List of regular arrays allows us to access their element by number. The first element of array @ food is $ food [0]. The
second element is $ food [1], and so on. But Perl also allows us to create arrays that are accessed by string. This is called
an associative array.

To define an associative array we use the usual parenthesis notation, but the array itself is preceded by a%. Suppose we
want 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 person's 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     108

Note that each list as an array of sign% has turned into a $ to access a particular element as a scalar element. Unlike list
arrays the index (in this case the name of the person) is enclosed in curly braces, the idea that associative arrays are
better 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 be
converted into an associative array by assigning to an associative array of variables. Ideally the list array will have an even
number 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
Operator
Associative array element does not have to (they are like hash tables) but is it possible to access all the elements in turn
using 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 of
the values of the array. These functions return a list of them in the same order, but this order has nothing to do with the
order of elements has dimasukkan.Ketika keys and values are called in scalar context they return the number of key / value
pairs 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 another
key / value pairs:

while (($person, $age) = each(%ages))
{
        print "$person is $agen";
}
Subroutines
Language Perl program allows users to define their own functions, called subroutines. They may be placed anywhere in
your 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 subroutines
called 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 parameters



Parameters
In the case of the above parameters are accepted but ignored. When subroutines called any parameters are passed as a
list in a special register array variable @ _. This variable is absolutely nothing to do with the scalar variable $ _. The
following 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 notation

sub 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.
Returning Values
Subroutines are always evaluated at the end. These subroutines return a maximum of two input parameters. An example of
its use follows.

sub maximum
{
        if ($_[0] > $_[1])
        {
                $_[0];
        }
        else
        {
                $_[1];
        }
}

$biggest = &maximum(37, 24);                      # Now $biggest is 37

The & printfirsttwo above subroutines also return a value, in this one. This is because the last thing s subroutines to do is
print statement and the results of a successful print statement is always 1.

Local Variable
Local Variable subroutines, and so of course are $ _ [0], $ _ [1], $ _ [2], and so on. Other variables can be made locally as
well, and is useful if we want to start changing the input parameters. The following subroutines test to see if there is one
string 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");                                            # true

In fact, even be smoothed by replacing the first two lines with

local($a, $b) = ($_[0], $_[1]);
Tutorial Bahasa Programm Perl Full Part

              Thanx’s to :
               Whitehat
               Wenkhairu
               Cyberheb
                 Scifix
            Prabujoyoboyo
              Darkslayers
                Shamus
             ./Blacknotes

Mais conteúdo relacionado

Mais procurados

Shell Scripting Tutorial | Edureka
Shell Scripting Tutorial | EdurekaShell Scripting Tutorial | Edureka
Shell Scripting Tutorial | EdurekaEdureka!
 
Bioinformatics p1-perl-introduction v2013
Bioinformatics p1-perl-introduction v2013Bioinformatics p1-perl-introduction v2013
Bioinformatics p1-perl-introduction v2013Prof. Wim Van Criekinge
 
perl usage at database applications
perl usage at database applicationsperl usage at database applications
perl usage at database applicationsJoe Jiang
 
Introduction to Perl - Day 2
Introduction to Perl - Day 2Introduction to Perl - Day 2
Introduction to Perl - Day 2Dave Cross
 
Perl 5.10 for People Who Aren't Totally Insane
Perl 5.10 for People Who Aren't Totally InsanePerl 5.10 for People Who Aren't Totally Insane
Perl 5.10 for People Who Aren't Totally InsaneRicardo Signes
 
Perl courseparti
Perl coursepartiPerl courseparti
Perl coursepartiernlow
 
LPW: Beginners Perl
LPW: Beginners PerlLPW: Beginners Perl
LPW: Beginners PerlDave Cross
 
Introduction to Perl - Day 1
Introduction to Perl - Day 1Introduction to Perl - Day 1
Introduction to Perl - Day 1Dave Cross
 
Strings,patterns and regular expressions in perl
Strings,patterns and regular expressions in perlStrings,patterns and regular expressions in perl
Strings,patterns and regular expressions in perlsana mateen
 
Scalar expressions and control structures in perl
Scalar expressions and control structures in perlScalar expressions and control structures in perl
Scalar expressions and control structures in perlsana mateen
 

Mais procurados (20)

Shell Scripting Tutorial | Edureka
Shell Scripting Tutorial | EdurekaShell Scripting Tutorial | Edureka
Shell Scripting Tutorial | Edureka
 
Perl Presentation
Perl PresentationPerl Presentation
Perl Presentation
 
Bioinformatics p1-perl-introduction v2013
Bioinformatics p1-perl-introduction v2013Bioinformatics p1-perl-introduction v2013
Bioinformatics p1-perl-introduction v2013
 
Perl Scripting
Perl ScriptingPerl Scripting
Perl Scripting
 
perl usage at database applications
perl usage at database applicationsperl usage at database applications
perl usage at database applications
 
Introduction to Perl - Day 2
Introduction to Perl - Day 2Introduction to Perl - Day 2
Introduction to Perl - Day 2
 
Perl 5.10 for People Who Aren't Totally Insane
Perl 5.10 for People Who Aren't Totally InsanePerl 5.10 for People Who Aren't Totally Insane
Perl 5.10 for People Who Aren't Totally Insane
 
PHP Web Programming
PHP Web ProgrammingPHP Web Programming
PHP Web Programming
 
Perl
PerlPerl
Perl
 
Perl courseparti
Perl coursepartiPerl courseparti
Perl courseparti
 
Perl
PerlPerl
Perl
 
LPW: Beginners Perl
LPW: Beginners PerlLPW: Beginners Perl
LPW: Beginners Perl
 
Perl Basics with Examples
Perl Basics with ExamplesPerl Basics with Examples
Perl Basics with Examples
 
Introduction to Perl - Day 1
Introduction to Perl - Day 1Introduction to Perl - Day 1
Introduction to Perl - Day 1
 
My cool new Slideshow!
My cool new Slideshow!My cool new Slideshow!
My cool new Slideshow!
 
slidesharenew1
slidesharenew1slidesharenew1
slidesharenew1
 
Perl_Part5
Perl_Part5Perl_Part5
Perl_Part5
 
Strings,patterns and regular expressions in perl
Strings,patterns and regular expressions in perlStrings,patterns and regular expressions in perl
Strings,patterns and regular expressions in perl
 
Introduction to Perl and BioPerl
Introduction to Perl and BioPerlIntroduction to Perl and BioPerl
Introduction to Perl and BioPerl
 
Scalar expressions and control structures in perl
Scalar expressions and control structures in perlScalar expressions and control structures in perl
Scalar expressions and control structures in perl
 

Semelhante a Tutorial perl programming basic eng ver

Beginning Perl
Beginning PerlBeginning Perl
Beginning PerlDave Cross
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to PerlDave Cross
 
PHP Powerpoint -- Teach PHP with this
PHP Powerpoint -- Teach PHP with thisPHP Powerpoint -- Teach PHP with this
PHP Powerpoint -- Teach PHP with thisIan Macali
 
CGI With Object Oriented Perl
CGI With Object Oriented PerlCGI With Object Oriented Perl
CGI With Object Oriented PerlBunty Ray
 
Introduction to Modern Perl
Introduction to Modern PerlIntroduction to Modern Perl
Introduction to Modern PerlDave Cross
 
What is the general format for a Try-Catch block Assume that amt l .docx
 What is the general format for a Try-Catch block  Assume that amt l .docx What is the general format for a Try-Catch block  Assume that amt l .docx
What is the general format for a Try-Catch block Assume that amt l .docxajoy21
 
Intermediate Perl
Intermediate PerlIntermediate Perl
Intermediate PerlDave Cross
 
Lecture 3 Perl & FreeBSD administration
Lecture 3 Perl & FreeBSD administrationLecture 3 Perl & FreeBSD administration
Lecture 3 Perl & FreeBSD administrationMohammed Farrag
 
P H P Part I, By Kian
P H P  Part  I,  By  KianP H P  Part  I,  By  Kian
P H P Part I, By Kianphelios
 
Advanced Perl Techniques
Advanced Perl TechniquesAdvanced Perl Techniques
Advanced Perl TechniquesDave Cross
 

Semelhante a Tutorial perl programming basic eng ver (20)

Lecture19-20
Lecture19-20Lecture19-20
Lecture19-20
 
Lecture19-20
Lecture19-20Lecture19-20
Lecture19-20
 
Beginning Perl
Beginning PerlBeginning Perl
Beginning Perl
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
 
PHP Powerpoint -- Teach PHP with this
PHP Powerpoint -- Teach PHP with thisPHP Powerpoint -- Teach PHP with this
PHP Powerpoint -- Teach PHP with this
 
CGI With Object Oriented Perl
CGI With Object Oriented PerlCGI With Object Oriented Perl
CGI With Object Oriented Perl
 
perltut
perltutperltut
perltut
 
perltut
perltutperltut
perltut
 
Perl slid
Perl slidPerl slid
Perl slid
 
Introduction to Modern Perl
Introduction to Modern PerlIntroduction to Modern Perl
Introduction to Modern Perl
 
Hashes Master
Hashes MasterHashes Master
Hashes Master
 
PERL.ppt
PERL.pptPERL.ppt
PERL.ppt
 
What is the general format for a Try-Catch block Assume that amt l .docx
 What is the general format for a Try-Catch block  Assume that amt l .docx What is the general format for a Try-Catch block  Assume that amt l .docx
What is the general format for a Try-Catch block Assume that amt l .docx
 
Php Learning show
Php Learning showPhp Learning show
Php Learning show
 
Perl_Part6
Perl_Part6Perl_Part6
Perl_Part6
 
Intermediate Perl
Intermediate PerlIntermediate Perl
Intermediate Perl
 
Lecture 3 Perl & FreeBSD administration
Lecture 3 Perl & FreeBSD administrationLecture 3 Perl & FreeBSD administration
Lecture 3 Perl & FreeBSD administration
 
P H P Part I, By Kian
P H P  Part  I,  By  KianP H P  Part  I,  By  Kian
P H P Part I, By Kian
 
Simple perl scripts
Simple perl scriptsSimple perl scripts
Simple perl scripts
 
Advanced Perl Techniques
Advanced Perl TechniquesAdvanced Perl Techniques
Advanced Perl Techniques
 

Último

The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxShobhayan Kirtania
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 

Último (20)

The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptx
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 

Tutorial perl programming basic eng ver

  • 2. A Basic Program Example : #!/usr/local/bin/perl # # Program to do the obvious # print 'Hello world.'; # Print a message Explaination : 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 run Comments and statements Comments can be entered into the program with the symbol # and the other was ignored except for the first row only way to stretch the comments of some of the lines is to use the # on each line Everything else is a Perl statement which must end with a semicolon, such as the last line above. Simple printing Print function outputs some information. In the above case it prints out a literal string Hello world. and of course end with a statement koma.Qta can find the above program produces an slightly unexpected result. So, the next thing to do is to run. Running The Program Type in the example program using a text editor and save it. Emacs is a good editor to use because it has its own Perl mode which 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 command chmod u+x progname at the UNIX prompt, where progname is the name of the program file. Now to run the program just type any of the following at the prompt.
  • 3. perl progname ./progname progname If something goes wrong then we can get the error message, or you might get something. We can always run this program without any warning using the command perl -w progname at the prompt. This will display a warning and the other (hopefully) helpful messages before trying to run the program. To run the program with a debugger use the command perl -d progname When the file is executed Perl first compiles and then runs the compiled version. So after a short pause for compilation the program should run quite fast. This also explains why we can get a compilation error when we execute a Perl file which consists 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 Variable The most basic type of variable in Perl is a scalar variable. Scalar variables hold both strings and numbers, and are remarkable 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 and underscores, but they do not have to start with the numbers and the variable $ _ is special, as we shall see later. Also, Perl is case sensitive, so $ a and $ A are different.
  • 4. Operation And Assignment Perl 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 it And for a string of Perl is like this $a = $b . $c; # Concatenate $b and $c $a = $b x $c; # $b repeated $c times To 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 $a Note that when Perl provides the value with $ a = $ b it makes a copy of $ b and then assign that to $ a. Therefore the next time you change $ b it will not alter $ a. Other operators can be found on pages furlough. Men leave the prompt type. Interpolation The 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 line print '$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. Double quotes force interpolation of any codes, including interpreting variables. It is much nicer than our original statement. Another code that interpolated include special characters such as newline and tab. Code n is newline and t is tab. Exercise This exercise is to rewrite the Hello world program so that (a) string is assigned to a variable and (b) the variable is then printed with a newline character. Use double quotes and do not use the concatenation operator .. Array Variables array variable is a list of scalar (ie numbers and strings). Array variables have the same format as scalar variables except that 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. Array is 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 scalar Array assignments in all of Perl, the same expressions in different contexts can produce different results. The first assignment below explodes the @ 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 statement push(@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 the following forms: push(@food, "eggs", "lard"); push(@food, ("eggs", "lard")); push(@food, @morefood);
  • 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 by changing the value of the variable $ special ". Variable is just one of many special Perl variable, most of which have strange names. 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 $#food Displaying Arrays Because context is so important, not surprisingly, has a lot of procedure with varying results print @food; # By itself print "@food"; # Embedded in double quotes print @food.""; # In a scalar context
  • 7. File Handling Here 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 file open(INFO, $file); # Open the file @lines = <INFO>; # Read it into an array close(INFO); # Close the file print @lines; # Print the array Open function opens the file for input (ie for reading). The first parameter is the filehandle which allows Perl to refer to a file in the future. The second parameter is an expression that shows the name of the file. If the given file name in quotes is taken literally without shell expansion. So the expression '~ / notes / todolist' will not be interpreted successfully. If you want 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, open statement can also specify a file for output and to add and feedback. To do this, prefix the name with the file> and >> for output to add: open(INFO, $file); # Open for input open(INFO, ">$file"); # Open for output open(INFO, ">>$file"); # Open for appending open(INFO, "<$file"); # Also open for input Secondly, if you want to print something to the file you have opened for output then you can use the print statement with an additional parameter. To print a string to a file using the filehandle INFO print 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 input open(INFO, '>-'); # Open standard output In the above program information is read from the file. File is the INFO file and to read from it Perl uses angled brackets. So the statement @lines = <INFO>;
  • 8. read the file denoted by the filehandle into the array @ lines. Note that the expression <INFO> read the whole file. This is because reading occurs in the context of an array variable. If @ lines is replaced by the scalar $ Lines is just one the next line will be read in. In either case each line is stored complete with its newline character at the end. Control Structure Perl supports many different types of control structures which tend to be like in C, but very similar to Pascal, too. Here we discuss some of them. Foreach To 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 value of 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 is empty to start with the block of statements is never executed. Testing The next few structures rely on a test being true or false. In Perl any non-zero number and non-empty string is counted as true. The number zero, zero by itself in a string, and the empty string are counted as false. Here are some tests on numbers and strings. $a == $b # Is $a numerically equal to $b? # Beware: Don't 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. For Perl 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 Until The following is a program that reads some input from the keyboard and will not continue until it is the correct password #!/usr/local/bin/perl print "Password? "; # Ask for input $a = <STDIN>; # Get input chop $a; # Remove the newline at end while ($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 is an 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 remove the 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 expression evaluates to true. Are useful while others are placed or until check at the end than at the beginning of the block statement. This would require the presence of the operator to mark the beginning of the block and the test at the end. Once again the message in the above password program then it can be written like this.
  • 10. #!/usr/local/bin/perl do { "Password? "; # Ask for input $a = <STDIN>; # Get input chop $a; # Chop off newline } while ($a ne "fred") # Redo while wrong input Conditionals Of 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 also possible 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. String Matching One of the most useful features of Perl (if not the most useful feature) is its powerful string manipulation facilities. At the heart of this is the regular expression (RE) which is shared by many other UNIX utilities. Reguler Expression Regular expression is contained in slashes, and matching occurs with the operator ~ =. The following expression is true if the 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 $ sentence The $_ special variable This time we will use as a Conditional if ($sentence =~ /under/) { print "We're 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 avoid using the match and non-match operators and above can be written simply as if (/under/) { print "We're talking about rugbyn"; } $ Variable is the default form for the operation of Perl, a lot and tend to be used
  • 12. More on REs In 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 character and 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 line e$ # e at the end of a line tle$ # tle at the end of a line und* # 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 letters At 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. 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 char n # A newline t # A tab w # 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, etc S # Any non-whitespace character b # A word boundary, outside [] only B # No word boundary Clearly characters like $, |, [,), , / and so on are peculiar cases in regular expressions. If you want tmatch to any of them then 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 backslash Some 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. Substitution And Translation As well as identifying regular expressions Perl can make substitutions based on the match. The way to do this is to use functions designed to mimic the way substitution is done in a text editor vi. Once again the match operator is used, and once 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, only s/london/London/ Note that two regular expressions (london and London) are surrounded by a total of three slashes. The results of this expression is the number of substitutions made, so it is either 0 (false) or 1 (true) in this case. Options This example only replaces the first string, and maybe that there will be more than one such string we want to replace. To make a global substitution last slash is followed by ag as follows: s/london/London/g the which of course can be used in the $ Variable. Again the expression returns the number of substitutions made, which is 0 (false) or something greater than 0 (right). If we want to also replace London, London, London and so on then we can use s/[Ll][Oo][Nn][Dd][Oo][Nn]/London/g but an easier way is to use the i option (for "ignore"). Expression s/london/London/gi will make a global substitution ignoring case. I also used the option in the / ... / regular expression match.
  • 15. Remembering Paterns It's often useful to remember patterns that have been matched so that they can be used again. It just so happens that anything matched in parentheses will be remembered in the variable $ 1, ..., $ 9. This string can also be used in the same regular 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. Variable variables $ 1, ..., $ 9 are read-only Another example of his if (/(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 regular expressions and as $ 1 for the entire program. The following swaps the first and last character of the line in the variable s/^(.)(.*)(.)$/321/ The ^ and $ match the beginning and end of the line. Storing code 1 character first, while the 2 code stores everything else up to the last character code stored in 3. Then that whole line is replaced with 1 and 3 After matching, coz can use the special read-only variables $ `and $ & and $ 'to find what works before, during and after the search. So after. $_ = "Lord Whopper of Fibbing"; /pp/; Finally on the subject of remembering patterns it's worth knowing that in the slashes of a match or a substitution variables are 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 $ searchre variable. Instead we should put the variable name in curly braces so that the code becomes $search = "the"; s/${search}re/xxx/;
  • 16. SPLIT A very useful function in Perl, which is divided into a string and place it into the array. Function using regular expressions and the usual work on the $ _ variable unless otherwise specified Split 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 of characters - that is an array of strings of length 1.
  • 17. Associative Arrays List of regular arrays allows us to access their element by number. The first element of array @ food is $ food [0]. The second element is $ food [1], and so on. But Perl also allows us to create arrays that are accessed by string. This is called an associative array. To define an associative array we use the usual parenthesis notation, but the array itself is preceded by a%. Suppose we want 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 person's 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 108 Note that each list as an array of sign% has turned into a $ to access a particular element as a scalar element. Unlike list arrays the index (in this case the name of the person) is enclosed in curly braces, the idea that associative arrays are better 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 be converted into an associative array by assigning to an associative array of variables. Ideally the list array will have an even number 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. Operator Associative array element does not have to (they are like hash tables) but is it possible to access all the elements in turn using 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 of the values of the array. These functions return a list of them in the same order, but this order has nothing to do with the order of elements has dimasukkan.Ketika keys and values are called in scalar context they return the number of key / value pairs 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 another key / value pairs: while (($person, $age) = each(%ages)) { print "$person is $agen"; }
  • 19. Subroutines Language Perl program allows users to define their own functions, called subroutines. They may be placed anywhere in your 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 subroutines called 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 parameters Parameters In the case of the above parameters are accepted but ignored. When subroutines called any parameters are passed as a list in a special register array variable @ _. This variable is absolutely nothing to do with the scalar variable $ _. The following 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 notation sub 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. Returning Values Subroutines are always evaluated at the end. These subroutines return a maximum of two input parameters. An example of its use follows. sub maximum { if ($_[0] > $_[1]) { $_[0]; } else { $_[1]; } } $biggest = &maximum(37, 24); # Now $biggest is 37 The & printfirsttwo above subroutines also return a value, in this one. This is because the last thing s subroutines to do is print statement and the results of a successful print statement is always 1. Local Variable Local Variable subroutines, and so of course are $ _ [0], $ _ [1], $ _ [2], and so on. Other variables can be made locally as well, and is useful if we want to start changing the input parameters. The following subroutines test to see if there is one string 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"); # true In fact, even be smoothed by replacing the first two lines with local($a, $b) = ($_[0], $_[1]);
  • 21. Tutorial Bahasa Programm Perl Full Part Thanx’s to : Whitehat Wenkhairu Cyberheb Scifix Prabujoyoboyo Darkslayers Shamus ./Blacknotes