Perl Tutorial
Results 1 to 2 of 2

Thread: Perl Tutorial

  1. #1
    Banned
    Join Date
    Jun 2003
    Posts
    1,302

    Perl Tutorial

    PerlTurorial



    Welcome once again, to one of my boring and outrageously stupid ass
    tutorials. As always if you have a problem with anything I say, show me where I am wrong.


    My references for this are Learn Perl in 21 days, and the official perl
    website. www.perl.com I also have a couple tutorials that I read, but
    all that info is for other stuff. Mainly if I write a second Tutorial.
    All the charts came from teach yourself Perl in 21 days, I just copied
    them from the book.


    Ok before you can start learning the langauge you are going to need an
    interpreter. To be honest, I have never written anything in perl on
    Windows, so I am not positive about the interpreter, and how it works.
    But go to www.perl.com for windows and the interpreter.

    If you are on a *nix system 9 times out of 10 perl is already installed on
    your system. To check do whereis perl on a command line interface. If
    you get anything besides "perl:" perl is installed and ready to go.
    To start a script just do pico <whatevertitleyouwant>. You can use vi
    also, I just prefer pico.

    This time when we come together we come together we are here to teach you
    fine people perl. I am personally working on the langauage. I haven't
    gotten really great at it, but I can write some nice scripts. I like the
    language. I actually prefer it to C.

    Well without further waiting let's start.

    HISTORY: Perl was created in 1987 by Larry Wall, Larray Wall was working on a tash for
    which the Unix program awk wasn't powerful enough, but he realized the task would tkae a
    whole lot of work to accomplish in a language like C. So perl was created as a scripting
    language that borrows several things from various other Unix tools. (You will understand
    this on the second one, when I introduce commands like "grep".

    Perl: Is an acronym which stands for "Pratical Extraction and Report Language"
    Which is an exact explanation of the langauges main goal. Perl is mainly used for extracting
    information/data from files.

    So what your wondering now, is why in the hell would I want to learn perl.
    Well that answer to that question is going to going to be on you. Though
    I can try to help you out. Reasons I choose to learn perl. If you are a
    system admin, it become very useful for clearing up disk space. (My own
    personal reason is, I wanted to write an IRC bot from scratch. Which I
    will be posting the code to, in a couple of days or weeks.)

    Another reason perl is good to learn is, because it is a high-end
    langauge, it is portable to other Platforms. Meaning if you code
    something on a *nix system you can take that same app (In most
    instances.)and take it over to a windows environment and use it.

    IMHO Perl is a very easy langauge to learn, most other high end langauges
    have too much BS you have to learn, a good thing about perl is that you
    don't have to differ between int, long int, etc... (You C programmers will
    know how much hell that is.) I will be honest once you get past the basic things of the
    language you will start to think that the language is the devil, there are a lot of
    instances where you just will want to hit your computer, but that goes with any langauge.

    Well I think that is enough just blabbing about BS, now it is time to
    actually learn the langauge.



    I won't be using this in my code here because I explain everything, but the # symbol is the
    symbol you use for comments, it's the exact same ass C++ // function.
    Whatever you put on a line after the # is considered and will be ignored by the
    interpreter. You should get used to commenting in your code. It is very helpful for when
    someone is looking at your code to understand what the hell is going on. That and when you
    look back on your own code it helps you remember what you were doing. I don't know how
    many times I have looked back on code that I have written and thought, what the hell was I
    smoking or doing when I wrote that code, because I left it uncommented.


    I guess it is time to do the overly done, Hello World program, which everyone knows and
    loves.

    Code:
    #!/usr/bin/perl -w
    
    print "Hello, World!!!\n";
    Ok the last example of code the Hello World program, we all know and love
    it. Now I am going to explain it to you. The first line "#!/usr/bin/perl
    -w" Is the shebang, the sh for the hash "#" and the bang for the exclamation point "
    !". Well everything but
    the "-w". The "-w" is there to turn on perl warnings, which are a great
    thing to have on because they help you see where you make mistakes at.
    Just remember to put "#!/usr/bin/perl" at the begining of your scripts it is needed.

    To explain what actually happens. When you run your script what will happen is your OS
    will look at the top line and that will tell it to run the script and where to look for your
    perl interpreter.

    Now the next line in that code is kind of self explanatory. The "print" function does just
    what it says, print. (For you C programmers you can use "printf" it just isn't as powerful
    as it is in C, you should try to become familiar with "print".) So the info that you
    enclose within the qoutes will be printed to the standard output, which in this case is
    your monitor. Now you can use single or double qoutes for the print function, which one
    you use depends on you and what you want to do. Single qoutes will not do variable
    interpolation. Which is a fancy way of saying change the value that your variable holds
    when you use a variable. Double qoutes will do variable interpolation.

    Here is a better way to look at variable interpolation.

    Code:
    #!/usr/bin/perl -w
    
    $hi = 'Hi how are you?';
    
    print '$hi\n';
    print "$hi\n";
    If you didn't catch what happened there, if you use single qoutes, the interpreter will
    pring $hi on the top one, and if you used the double qoutes you will get "Hi how are you".
    Now in that instance I something that I haven't showed you yet. That is the "\n". That is
    an escape character. What happens when your interpreter gets to that point it will see
    "\n" kill the end of the line that you are on. Whichever line you are on will end. One
    other thing, you need to end most statements that you use in perl with a ";" semicolon,
    there are instances where you won't use it, I will show you some of those instances.


    A good reason to use single qoutes instead of double qoutes is single qoutes will not use
    escape characters. It is also better if you are trying to explain where to look for
    something. Say you wanted to tell someone in a script to look in /etc/passwd for a list of
    all users on the system with a password. If you used double qoutes you would have to
    escape the "/". So it would end up being something like

    Code:
    print "Look in \/etc\/passwd";
    Instead of

    Code:
    print 'Look in /etc/passwd';
    Now in that instance I said something about escaping, escaping is what you do if you want
    to work against the interpreter. If you use /e in that instane it will escape. Which
    isn't what you want to do. What you want to do is say look in a file. So if you put a
    backslah infront of the forward slash it will escape that escape character. You can do the
    same thing for scalars, arrays, and hashes(Which I will probably talk about hashes in the
    next tutorial.)

    So say you wanted to write in your script that $hi is equal to the value of 'Hi, How are
    you". You would have to either use single qoutes or just escape the character by doing.

    print "\$hi is equal to Hi how are you";




    Perl Escape Characters For strings:

    Code:
    \n 		Newline
    \r		Carriage return
    \t		Tab
    \f		Formfeed
    \b		Backspace
    \a		Bell (Special one, that will sound a bell on your system.)
    \e		Escape
    \0nn		Octal (where nn are digits)
    \xnn		Hexadecimal(where nn are 0-9, a-f or A-F)
    \cX		Control chanracters, where X is any character (for example, \cC is 
       		equivalent to COntrol-C)
    \u		Make next letter uppercase
    \l		Make next letter lowercase
    \U		Make all following letters uppercase
    \L		Make all following letters lowercase
    \Q		Do not match patterns(regular expressions only) (I will explain what regex
    		is in the next tutorial)
    \E		End

    That is a list of all the Escape characters for strings, don't try to remember them all.
    You won't even use most of them. "\n" "t" are pretty much the only ones you will use most
    of the time.

    Scalar Variables:

    Ok now one of the interesting things about perl is it's ability to convert between numbers,
    strings, floating point and characters. Perl only distinguishes between scalar data and
    list variables.

    Numbers:
    These are all valid numbers.

    Code:
    9
    7.6
    .3333333
    5.
    1_2_3_5
    There are other numbers that are valid but I will save those for the second tutorial. Perl
    doesn't really care about the differnece between floating point and integers. It reads
    them all the same. So no int this or float that. w0000t

    I am going to go over a couple math assignment operators, now.

    ARITHMETIC OPERATORS:

    Code:
    +	Addition			3+4		
    -	Subtraction			4-2		
    	Negative Operator		(-10) 
    *	Mulitplication			5*5
    /	Division			10/5
    **	Exponent			4**5
    %	Modulus(remainder)		15%4
    Ok, now that you know those, you need to understand about how to control between floating
    point and integers. It will be needed at some point.

    Let's say you do something like.

    $hello = 10 / 3;
    3.33333333

    Wow nice answer hugh? Nice and long, but wait you don't want that long of an answer.
    Well what you would do to edit your answer so that you would only get an integer would be.

    $hello = int 10/3;

    That will get you just a normal 3 answer. Now there are other ways of editing that number.

    One such way is to use printf (I see all you C programmers jumping up and down).

    I will quickly go over how to do that but, I am going to say using the printf function is
    an area that I won't go much over. I will probably go over that and other functions in the
    next tutorial.

    Let's say that you wanted that answer to show 2 decimal points. Well what you do is.

    printf (%.2f, 10/3);

    What that does is, it will take the value you and cut off all the value after the decimal
    point except for 2 numbers.

    If you would like to do that expression so that you get a whole number while using the
    printf function. You would do:

    printf ("%d", 10/3);


    Ok you were probably wondering what the code I printed a while was for and what it did.

    Well what happened in that script is, that I called a scalar variable. A scalar variable
    is shown by the "$" money, symbol. Followed by a alphanumeric or underscores. You don't
    have to declare or intialize variables in perl, unlike C. Though you should anyway so you
    have a good record of which ones you have. If you intiallize a variable and don't use it
    (and have perl warnings on.) it will give you a warning, telling you that you didn't use the
    variable that you intiallized. Variable names are case sensitive so $hi, $Hi, and $HI are
    all different variables. Whenever you declare a variable you have up to 255 charateres to
    use for it's name. (I personally think you are ****ing crazy if you use, 255 characters
    for a variables name, but hey go crazy trying to figure out one, let me know which ones
    figure out. Also if you don't declare a variable and use it, you will get a warning.


    Ok I should explain the difference between a couple things. When doing math, or anything.
    You have to know the difference between an assignment operator and a conditional test.
    What I mean by this is if you use "=" it is assigning whatever value is on the right side
    of the "=" to the variable on the left.

    So, something like.

    Code:
    #!/usr/bin/perl -w
    
    $hi = 'Hi, how are you';
    Hi, how are you, is being assigned to the variable $hi. This becomes important when you
    start testing for things. When I talk about "if" "while" and other testing variables this
    will make a lot more since. Just for now remember that if you are assigning the value of
    something to a variable. You have to put that variable on the left side of the "=" sign.


    Well I guess I will do the fahrienhiet to Celsiuis program. Since everyone has it
    somewhere.

    Code:
    #!/usr/bin/perl -w
    
    $fahr = 0;
    $cel = 0;
    
    print "Enter a temperture in Fahrenheit: ";
    chomp($fahr = <STDIN>);
    $cel = ($fahr * 32) * 5/9;
    print "$fahr degrees Fahrenheit is equivalent to ";
    printf ("%d degrees Celsius\n"; $cel);
    As you might of noticed I intiallized $fahr and $cel to the value of 0, if you are taking
    data from an outside source. i.e. person, file whatever. You can set it to empty qoutes
    also.

    Now that is the fun script for the moment. I have to give you guys something to do with
    your recently learned knowledge. The only thing that you shouldn't know what is or how it
    works are the chomp and <STDIN>. Give me a second and I will explain them both.

    Everything else in that script you should understand.


    So your wondering what the hell a chomp is. Well chomp is a function in perl that is kind
    of special and very helpful. I will show you an example and then explain to you what it
    does.

    Code:
    #!/usr/bin/perl
    
    $hi = "Hello, how are you\n";
    chomp ($hi)
    
    print "$hi";
    Ok the chomp function takes off a \n escape. The way it works is, the chomp function will
    see the \n in your code in whatever variable you assign it to check and it will remove it.

    Now chomp, has a cousin called chop, and chop is good just a bit more of an *******. Chop
    removes the last character of the variable it is checking no matter what it is. So if you
    have a space at the end chop, will remove the space, it will also remove the "u"
    at the end of "Hi, how are you".

    The other function that you are wondering what it does is the <STDIN> variable. That one
    is going to be your friend. You are going to use it over and over and over etc...

    That is the standard input function. Now the standard input that it grabs is, from your
    keyboard. Notice how "STDIN" is in all caps. That is intentional.

    Now remember when I said assigning values to variable. Well thats what <STDIN> does it
    will assign it's value to whatever variable you tell it too.

    (Kind of a note for you guys what <STDIN actually does is it grabs the input from your
    keyboard and places that value in a special variable "$_" then it takes the value from
    there and assigns it to, whatever variable you tell it to.)

    So let's say you want to, get some info. From someone. You could do something like.

    Code:
    #!/usr/bin/perl -w
    
    $pay = "";
    
    print "Enter how much you make an hour";
    $pay = <STDIN>;
    chomp($pay);
    Notice how I called chomp and STDIN on different lines unlike the example I did earlier.
    Well you can do that, chomp is only checking the variable, "$pay" so it doesn't need to be
    on the same line as the <STDIN>.

    Now if you have been following along, what just happened there is you assigned, whatever
    the person said there pay is to "$pay".

    (Another note, there is no check to make sure the person entered a number, perl will take
    whatever they enter.")

    Now we are going to modify that script to be a bit better, and more useful.

    Code:
    
    #!/usr/bin/perl -w
    
    $pay = "";
    $hour = "";
    $gross = "";
    
    
    print "Enter how much you make an hour:";
    $pay = <STDIN>;
    chomp($pay);
    
    print "Enter how many hours you work a week:";
    $hour = <STDIN>;
    chomp($hour);
    
    
    $gross = $pay * $hour;
    
    print "$gross";
    Now there you go, you now have a script to tell you how much you will make, if you put in
    how many hours you work and how much you make an hour. Somewhat useful.

    Well we have since this thing has been long enough already, what I am going to do is, just
    show you a little more and save the rest for the next tutorial.


    EQUALITY AND RELATIONSHIP OPERATORS:

    Code:
    Test			Numeric Operator		String Operator
    
    equals			==				eq
    not equals		!=				ne	
    less than		<				lt	
    greater than		>				gt
    less than or equals	<=				le
    greater than or equals	>=				ge
    Those will come in handy when comparing numbers and strings. As I said earlier perl will
    convert between a string and a number. So for instance if you are doing something and you
    use "eq" when you should use == perl will continue working. (If you have warnings on it,
    will tell you that you messed up.)

    All of those operators are pretty much for testing instances of things. Such as to test
    and see if the amount you make is enough to pay your bills.

    There is another set of operatorsand they are Logical Operators.

    LOGICAL COMPARISONS

    Code:
    &&			and		logical AND
    ||			or		logical OR
    !			not		logical NOT
    Now all these will come in handy when comparing different expressions.

    Well I guess it is time that I introduce you to your, new best friend.

    if (test) {

    }


    That will become one of your most used statements. There are actually several others that
    go with the if set, but this has been long enough as is, I will go over them in the next
    one.

    Ok so I showed you what it is but not how to use it. Well let's take that little script we
    wrote up for pay.

    Code:
    #!/usr/bin/perl -w
    
    $pay = "";
    $hour = "";
    $gross = "";
    $bills = "";
    
    
      print "Enter how much you have to pay out in bills this week:";
    	$bills = <STDIN>;
    	chomp($bills);
    
    
      print "Enter how much you make an hour:";
    	$pay = <STDIN>;
    	chomp($pay);
    
      print "Enter how many hours you work a week:";
    	$hour = <STDIN>;
    	chomp($hour);
    
    $gross = $pay * $hour;
    
    if ($gross == $bills) {
    
    print "You won't be going to the movies this week.\n";
    }
    if {$gross <= $bills) {
    
    print "Going to be a little tight on cash, might want to try avoid driving in front of";
    print "McDonald's";
    
    $fun = $bills - $gross;
    
    print "You will owe $fun dollars";
    }
    
    if ($gross >= $bills) {
    
    print "You should have a little extra cash this go around, not sure how much."
    
    $fun = $bills - $gross;
    
    print "You will have $fun , left to play with.";
    }
    Now what happens in that code is perl examines all that code and it goes over the test
    starting at the top an working it's way down, so if the first if statement comes back true,
    then the rest of them are ignored. Now if the first comes back true, all the info in the {}
    will be run. If not it won't get run. If the first one comes back
    false then it goes on to the next block of code. Notice how there is no semicolon after
    the if statement. That is correct, you don't use one on if statements.

    Now after all that talking, and all your reading, I am guessing I will end here. There is
    a lot that I left out of this one, but I figured that would be a good start. I will write
    a second sometime this week, and add in all the little things I left out, plus a lot of
    other things.





    Wait!!! Where do you think your going???

    Oh you think it was going to be that easy, oh no. Your not getting off that easy. You
    have work to do. I have a couple questions for you.

    1. What is the difference between double and single qoutes?
    2. What are the 2 kinds of data you can use in perl?
    3. What is a # used for in perl?
    4. What does != mean?
    5. What does the escape character \n do?
    6. How do you escape an escape, say you wanted to escape a \n how would you escape it?
    7. What does Perl stand for?
    8. Who created Perl?
    9. What does the &lt;STDIN&gt; function do?
    10. What is the standard input that &lt;STDIN&gt; takes input from?

    Ok, after all that reading your head has to hurt, I know I am tired of typing. I will say
    a couple side notes. Don't get used to how way that code looks, there are many ways to do
    anything in perl, and also, I didn't comment or even correctly space a lot of stuff in that
    tutorial. I have pretty shitty coding practices. I spend a bit of my time working on my
    own code going back and commenting it. So don't get used to see code that looks like that,
    I should of done a lot of things.

    I will decide if I will finish writing the second volume of this tutorial, in about a day
    or 2. Depending on the responce to this one. Of course, if you have any comments good or
    bad they are welcomed, but be forewarned if you say something about something I didn't say,
    remember who I am aiming to teach in this tutorial. Most of the stuff I didn't mention
    will be in the next 3 tutorials.

    Well with all that said and done, I think I am going to go find myself a beer somewhere and
    get drunk. Damnit I need some duvel.

    Your last assignment in this tutorial is to take that last script that you wrote and edit
    it to output, the number of hours you work in a month, and also do the math for a month.
    It is a very simple conversion. If you have any questions, please ask them or PM them to
    me.

    Besides that, later.

    /me walks off to get a BBB.

    --whiz


    I am also going to attach the file for you.

  2. #2
    Not bad... not bad at all.
    --> MyWebsite <--

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •