Perl Tutorial Part 1

Post by nullbyt3 on xx.xx.xx.xx
Perl has just bypassed python as my favorite language and I believe now that Perl is a better first language, and then python (for me anyway :) ). Here is a beginner's tutorial on Perl; it should grow over time as I get the time to keep going on with it.

Perl Tutorial Part 1:

The Hello, World script and what it means:

Code

#!/usr/local/bin/perl
use strict;
use warnings;

print "Hello,Worldn";







Anyone who has a little practice in any language knows it starts with this simple program. It usually, for the most part, looks the same in most lower level languages like python, perl, javascript, etc, but in actuality, all the languages are a little different, so let's break it down in Perl:

We start with the shebang line, which I'm going to skip and assume is already known. If your unfamiliar with shebang, it points to where perl is installed on your OS and looks like this:

Code

 #!/usr/local/bin/perl      # This is the shebang line, its used to point to the directory Perl is installed in.
                                 # It's not needed as much as it used to be, but still its considered a good programming
                                 # habit to use this anyhow.



Strict and warnings:

Code
     
use strict;
use warnings;



Ok, next we have use strict and use warnings, and I am going to go over both imports in one section because they kind of go hand and hand. These two modules are imported to help with the proper syntax of your Perl program, and it's considered good programming practice to use them. They help in many ways, one of which is with program security. By forcing you into separating lexical and Global variables, it stops arbitrary commands from being passed from Lexical variables to global variables:

a) Global variables are just that - Global. They are hard-coded or static variables, and are relevant throughout the program or script.

b) Lexical variables are temporary and start with "my" . There can be security issues with lexical variables if they aren't declared correctly. These variables die or fall out of the programs scope after the code moves to the next block; however, they can be referenced and brought back (This is out of the scope of this tutorial, but we will come across how to do this later).

Strict/Warnings also help by checking variables and syntax that may clash with future variables and syntax. If this section is scaring you or making Perl seem to complicated, you can skip over this section and move to the next lines. All you need to know at this point is to use strict and warnings, as they do help you to create better programs.

The string, Hello,World is enclosed in double quotes. Quotes play a big part in all Perl string literals. We see the n which tells perl too print the output of the program on a newline. Finally we see the semi-colon ( ; ) at the end of the string command, which simply signifies the end of a Perl command. Semi-colons are a big deal in Perl and are mostly used to end one command so another can begin, like in this easy program:

Code

 #!/usr/local/bin/perl
use strict;
use warnings;

print "This stringn";     #<-newlines 
print "will be printedn";
print "on four lines becausen";
print "that is what we want it to do.n";




We don't even need to separate the commands to separate lines, as long as the n tag is in place. Consider this script that should run with the same output as above:

Code

#!/usr/local/bin/perl
use strict;
use warnings;

print "This stringn"; print "will be printedn";
print "on four lines becausen"; print "that is what we want it to do.n";





The output of both scripts should be:

This string
will be printed
on four lines because
that is what we want it to do.

Perl, like most, if not all languages, also handles numbers and equations - those simple, and even to the more difficult. Consider this numeric script:

Code

#!/usr/local/bin/perl
use strict;
use warnings;

    print "9 + 9 = ", 9+9, "n";
    print "(3 + 3) * 8 = ", (3+3)*8, "n";
    print "9 + 5 * 6 = ", 9+5*6, "n";
    print "3 raised to the power of 9 is ", 3**9, "n";
    print "3/4 = ", 3/4, "n";



Output:

9 + 9 = 18
(3 + 3) * 8 = 48
9 + 5 * 6 = 39
3 raised to the power of 9 is 19683
3/4 = 0.75

I'm not going to go too deep into integers as its could be a tutorial in and of itself.

THINGS TO KNOW:

1) "Scalar" - The other side of the variable.
Example: $money(scalar) = 55.23(variable)

2) "Literals" - Perl has two types of scalar constants called "numeric literals" and "string literals."

NUMERIC AND STRING LITERALS:

3) "String Literals" - string literals use a sequence of characters like "Hello,World". You can use as much data as you want because strings have no limit except the size of your virtual memory. Strings can contain any kind of dats; Ascii, both simple and with high bits on, binary is used and strings can even be empty.

EXAMPLES OF ACCEPTABLE STRINGS:

a) "foobar"
b) 'Four score and seven years ago'
c) "One fish,nTwo fish,nPink fish,nPoo fish,n"
d) "" (which is an empty string)
e) "I said, eat shit. She said, after you my dear.n"

Use of double quotes in Perl strings:

a) "So I said to him, "Go ahead, make my day""

This won't work because of the placement of quotes so we add a backslash to properly tell perl your using quotes within quotes (There are other reasons in other situations, but for the moments all you need to know is escape the quotes in a double quote scenario).

b) "Then I said to him, "Go ahead, make my day.""

This is correct syntax, and it works the same in like situations where sets of double quotes are being used. Even in contractions like:

b1) 'Of course I'm elite.'

c) Double Quotes - In double quotes Perl looks for variable names and/or escape sequences.

c1) Escape sequences - special strings that allow you to embed characters in strings that allow to embed characters in strings when just typing the characters would cause problems. Perl escape sequences:

n - newline
r - carriage return
t - tab
b - backspace
u - Change next character to uppercase
l or 1 - Change next character to lowercase
- a literal backslash character
' - a literal 'inside of a string surrounded by single quotes(")
" - a literal " inside of a string surrounded by double quotes


d) Single Quotes - Single quotes are taken literal. Every character encased in the single quotes will be used exactly the way it's written, with the exception of "" in situations like b1.

4) "Numeric Literals" - Numbers, perl accepts many ways of writing numbers, for instance:

a) 6 - Integer
b) 12.5 - A floating point number
c) 20. - another floating point number
d) .612086 - yet another floating point number
e) 1e10 - Scientific notations
f) 5.67C - 23 - Scientific notation(e or E is acceptable)
g) 3_184_896E - large number with underscores instead of commas

Floating-point decimal numbers contain a decimal point in the correct position, even if there are no digits to the right of it. A floating-point number can be expressed in scientific notation as an exponent preceded by the letter e (or E), and a decimal number called the mantissa.

The value of the scientific-notation literal is 10 raised to the power indicated by the exponent, multiplied by the mantissa; for example, 6.5536E4 = 65,536.0.

(Strictly speaking, a mantissa is the decimal part of a logarithm, where it serves the same purpose as it does here.)

In numeric Literals you can't use numb

ers with 0 in the front like 010 because in Perl, a zero in the front of a numeric string represents an Octal number base 8

Having many quotation marks embedded in a string can make typing the string error-prone and difficult because each embedded quote mark has to be escaped, as shown here:


"I said, "Go then,", and he said "I'm gone."."


4) "Variables" - Variable names can contain alphabetic (a to z, A to Z) characters, numbers, or an underscore character (_) after the type identifier. The first character of a variable name can't be a number, though.

6)Scalar Variables - To store data in perl, you must use the scalar variable. In perl, a scalar variable is is indicated with a dollar sign ($Variable). Some examples include:

$a
$total
$Date
$Time
$serial_no
$dog450

But $44 is illegal.

Numeric scalars have special uses we will get to in later tutorials. Alone, as scalars, they are considered illegal.

7) Dollar sign or $ - called a type identifier, tells perl that a variable contains scalar data. Other variable types like hashes and arrays use a different identifier or no identifier at all (File handles). Variable names in Perl, whether hashes, arrays, filehandles, or scalars, must conform to the following rules:

- Variable names contain numbers, alphabetic (a-z or A-Z), or underscore after the type identifier, but the first character of a variable cannot be a number.

- Variable names are case sensitive. This means that upper and lowercase are significant in variable names. Each of the below represents a different scalar variable:

$value
$VALUE
$Value
$valuE

Perl reserves to itself single-character variable names that don't start with alphabetic characters or underscores. Variables such as $_, $", $/, $5, and $$ are special variables and should not be used as normal variables in Perl programs. Some of the purpose of these special variables will be show in 8.

Scalar variables in Perl do not have to be declared or initialized in any way before you can use them. To create a scalar variable, just use it. Perl uses a default value when an uninitialized variable is used. If it's used as a number (such as in a math operation), Perl will use the value 0 (zero); if it's used like a string (almost everywhere else), Perl will use the value "", the empty string.

8)Special Variables- Perl's special variables,$_, value is used as a default by many operators and functions. An example being, if you simply state "print" by itself without specifying a scalar variable or string literal to print. Perl will print the current value of $_ as so:

Code

$_="Perl is my new favorite language";   

print; #should print the value of $_ , which is, "Perl is my new favorite language" (will print w/o quotes)






The "For" Loop




1) The "for" loop allows us to loop through a sequence of numbers and repeat the operators of each number.

Consider the following script:

Code

#!/usr/local/bin/perl
use strict;
use warnings;

    for my $i (1..50)
    {
        print $i, "n";
    }





What this script does: This script will go through every value from 1 to 50 and print the output of each value to a new line as specified by the n or newline escape sequence. Note the value will loop til it hits 50 then terminate. The curly brackets {} will encapsulate the loop block. We can nest these loop blocks in programs when and where needed.

Consider the following script:

Code

#!/usr/local/bin/perl 
use strict;
use warnings;

for my $y (1 .. 30)
    {
     for my $x (1 .. 30)
        {
            my $product = $y*$x;
          
            for my $whitespace (1 .. (4-length($product)))       #use enough whitespace so the number will occupy 4 characters
            {
                print " ";
            }
            print $product;
        }
        print "n";     # Move to the next line
    }




Output:
h4x@slax:~/Desktop$ perl 11.pl
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54 56 58 60
3 6 9 12 15 18 21 24 27 30 33 36 39 42 45 48 51 54 57 60 63 66 69 72 75 78 81 84 87 90
4 8 12 16 20 24 28 32 36 40 44 48 52 56 60 64 68 72 76 80 84 88 92 96 100 104 108 112 116 120
5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95 100 105 110 115 120 125 130 135 140 145 150
6 12 18 24 30 36 42 48 54 60 66 72 78 84 90 96 102 108 114 120 126 132 138 144 150 156 162 168 174 180
7 14 21 28 35 42 49 56 63 70 77 84 91 98 105 112 119 126 133 140 147 154 161 168 175 182 189 196 203 210
8 16 24 32 40 48 56 64 72 80 88 96 104 112 120 128 136 144 152 160 168 176 184 192 200 208 216 224 232 240
9 18 27 36 45 54 63 72 81 90 99 108 117 126 135 144 153 162 171 180 189 198 207 216 225 234 243 252 261 270
10 20 30 40 50 60 70 80 90 100 110 120 130 140 150 160 170 180 190 200 210 220 230 240 250 260 270 280 290 300
11 22 33 44 55 66 77 88 99 110 121 132 143 154 165 176 187 198 209 220 231 242 253 264 275 286 297 308 319 330
12 24 36 48 60 72 84 96 108 120 132 144 156 168 180 192 204 216 228 240 252 264 276 288 300 312 324 336 348 360
13 26 39 52 65 78 91 104 117 130 143 156 169 182 195 208 221 234 247 260 273 286 299 312 325 338 351 364 377 390
14 28 42 56 70 84 98 112 126 140 154 168 182 196 210 224 238 252 266 280 294 308 322 336 350 364 378 392 406 420
15 30 45 60 75 90 105 120 135 150 165 180 195 210 225 240 255 270 285 300 315 330 345 360 375 390 405 420 435 450
16 32 48 64 80 96 112 128 144 160 176 192 208 224 240 256 272 288 304 320 336 352 368 384 400 416 432 448 464 480
17 34 51 68 85 102 119 136 153 170 187 204 221 238 255 272 289 306 323 340 357 374 391 408 425 442 459 476 493 510
18 36 54 72 90 108 126 144 162 180 198 216 234 252 270 288 306 324 342 360 378 396 414 432 450 468 486 504 522 540
19 38 57 76 95 114 133 152 171 190 209 228 247 266 285 304 323 342 361 380 399 418 437 456 475 494 513 532 551 570
20 40 60 80 100 120 140 160 180 200 220 240 260 280 300 320 340 360 380 400 420 440 460 480 500 520 540 560 580 600
21 42 63 84 105 126 147 168 189 210 231 252 273 294 315 336 357 378 399 420 441 462 483 504 525 546 567 588 609 630
22 44 66 88 110 132 154 176 198 220 242 264 286 308 330 352 374 396 418 440 462 484 506 528 550 572 594 616 638 660
23 46 69 92 115 138 161 184 207 230 253 276 299 322 345 368 391 414 437 460 483 506 529 552 575 598 621 644 667 690
24 48 72 96 120 144 168 192 216 240 264 288 312 336 360 384 408 432 456 480 504 528 552 576 600 624 648 672 696 720
25 50 75 100 125 150 175 200 225 250 275 300 325 350 375 400 425 450 475 500 525 550 575 600 625 650 675 700 725 750
26 52 78 104 130 156 182 208 234 260 286 312 338 364 390 416 442 468 494 520 546 572 598 624 650 676 702 728 754 780
27 54 81 108 135 162 189 216 243 270 297 324 351 378 405 432 459 486 513 540 567 594 621 648 675 702 729 756 783 810
28 56 84 112 140 168 196 224 25
2 280 308 336 364 392 420 448 476 504 532 560 588 616 644 672 700 728 756 784 812 840
29 58 87 116 145 174 203 232 261 290 319 348 377 406 435 464 493 522 551 580 609 638 667 696 725 754 783 812 841 870
30 60 90 120 150 180 210 240 270 300 330 360 390 420 450 480 510 540 570 600 630 660 690 720 750 780 810 840 870 900


Lets take a look and see what this script does by using the For loop. First of all, the # sign is used for comments or notes of explanation, clarification, or for understanding, left by the programmer to help himself or other people using the program. Now, this script has 2 scalar variables, $y and $x. This script takes variables $y and $x and neatly shows us the multiples. With $y being equal to 30 and $x being equal to 30 the multiples in between are shown til we reach 900. Also, note how we are encapsulating two separate expressions in two separate sets of brackets.



The IF/ELSE Statement




The syntax of an "if" statement is pretty much the same in most languages and follows this example:

if (expression) block

or

if (expression is true) execute block of code: If the expression is true the block of code is executed, if the expression is false the code isn't executed. Then we can add the "else" statement in the event the expression is false. Sounds simple enough, right?

Here's a simple script using the if statement:

Code

#!/usr/local/bin/perl 
use strict;
use warnings;

my $a=1;

  if ( $a == 1 ) {
       
        print "Well it appears this statement is true, a is equal to $a.n";

    }





Now, as we can see right off the bat the $a is given the value of 1 which makes the statement true, therefore executing the block of code beneath. Remove the $a=1 assigned value and run the script again and see what happens. Without the assigned value the code will not execute, which is where the all powerful "ELSE" comes in. Check out the script below:

Code

#!/usr/local/bin/perl 
use strict;
use warnings;

   my  $b=1;

    if ( $b == 2 ) {

       print "I think cats are better then dogs.n";
      }
    else
      {
       print "Its obvious that dogs are better then cats.n";
      }




This program returned false, and therefore executed the second block of code stating the fact that dogs are indeed better then cats. These scripts are simple uses of the If/else expressions, but these expressions lay the groundwork for most in depth programming. The next is the ELSE IF statement which is used when there are more then two expressions.

Code

#!/usr/local/bin/perl 
use strict;
use warnings;

    my $a=1;
    my $b=2;
    my $c=3;

    print "Please enter a number from 1 to 3:n";
    my $number = <>;
    chomp $number;
    if ( $number == 1 ){

        print "You picked no. $an";
    }
    elsif ( $number == 2 ) {
        print "You picked no. $bn";
    }
    elsif ( $number == 3 ){

        print "You picked no. $cn";
    }




Now as you may have noticed I added a conditional statement where you were asked to pick a number from 1-3 and the depending on which number you picked, it returned the number to you. I hope any new programmers are starting to see where this is going and how if/elsif/else/etc leads to deeper programming. Now we have made a simple program that when given input will execute a block of code depending on the users choice.


The next tutorial we will go into conditional statements and make some more in-depth programs.

No comments:

Post a Comment