הלינקייה: מגזין חודשי למפתחים

רוצה לשמוע על כל האירועים, המדריכים, הקורסים והמאמרים שנכתבו החודש ?
הלינקייה הינו מגזין חופשי בעברית שמשאיר אותך בעניינים.
בלי ספאם. בלי שטויות. פעם בחודש אצלך בתיבה.

Getting Started

"We think that Perl is an easy language to learn and use, and we hope to convince you that we're right. One thing that's easy about Perl is that you don't have to say much before you say what you want to say" -- Programming Perl, 3rd Ed.

Perl's simplicity aims to provide both novice and professionals with the tools to get their jobs done, quickly.
This first example demonstrates using perl to calculate the average of two numbers read from the user.

What We Have So Far:

  1. use Modern::Perl in the begining makes perl more maintainable, by providing us with some new language features and restricting some old (depracated) habits some programmers had. We'll talk about that a lot during the course. If you're using perl 5.8 or older, use strict and warnings instead.
  2. Commenting. We use a # sign for single line comments, and POD syntax for multi line comments. a POD comment begins with a =pod and ends with a =cut line.
    There are tools that translate these comments into HTML documentation (just like javadocs).
  3. use strict;
    use warnings;
     
    # say is a new feature provided by the use Modern::Perl
    print "Hello. Please type in two numbers for the calculation\n";
     
    # reading user input is handled with the <> operator. It takes a filehandle 
    # and reads a single line from it, in this case we use STDIN to refer the 
    # standard input
     
    my $a = <>;
    chomp $a;
     
    my $b = <>;
    chomp $b;
     
    my $avg = ($a + $b) / 2;
     
    print "The average of $a and $b is $avg\n";
    

    It's worth noting that function calls are usually performed without parenthesis. In perl, parenthesis are optional when calling a function, and in simple cases they are usually omitted for readability.

    Perl Variables

    Perl's variables "carry" their type with them in code for readability considerations. The basic variable type is called a scalar, and every scalar variable starts with a $ sign. The $ is called a sigil and it is part of the variable name - every time we use a scalar we must relate to it with the $.
    The second thing you can notice about the sample program is the "my" keyword. Each time we introduce a new variable into perl, we need to declare its scoping rules - whether it is a local or global variable. We start with "my" for local variables.
    A "my" variable can be used after its declaration and until the end of the block.

    Perl allows us to store a single value in a scalar variable, either a number or a string. Perl will automatically try to convert that value to its "right" type by the context. Examine the following examples:

    use strict;
    use warnings;
    
    my $first_name = "Ynon";
    my $last_name = "Perek";
    
    # works - variables are interpolated as text inside double quotes
    my $full_name = "$first_name $last_name";
    
    my $x = 8;
    my $y = 4;
    
    # works - the plus (+) operator performs numeric operation 
    my $z = $x + $y;
    
    # $xy is now 84. The dot (.) operator performs string concatenation
    my $xy = $x . $y;
    
    # $bug will take the value 0, because $first_name and $last_name cannot be evaluated as numbers
    my $bug = $first_name + $last_name;
    
    

    Flow Control

    Most basic flow control works as expected by c/java developers. It's possible to use if, while and for just as you would in other languages. One thing to keep in mind - the curly braces are mandatory in the long form of the flow control.
    Examine the following:

    # Long if, the curly braces are mandatory
    if ( 2 < 3 ) {
      print "All is well\n";
    } 
    
    # Short form, no need for braces
    print "All is well\n" if 2 < 3;
    

    There are two sets of comparison operators, one for comparing strings and the other for comparing numbers, as in the following table:

    Operation Numbers Compare String Compare
    Equal == eq
    Less Than < lt
    Greater Than > gt
    Not Equal != ne

    Other flow control structures include for and while, as in the following code example:

    # Read text from standard input until end-of-input char is encountered
    # print the total length of the input read
    my $total = 0;
    while ( my $line = <> ) {
      chomp($line);
      $total += length($line);
    } 
    print "Total chars: $total\n";
    
    # prints all numbers from 0 to 9
    for (my $i=0; $i < 10; ++$i ) {
      print "$i\n";
    }
    
    

    Useful Perl Idioms

    The following idioms are used often enough in perl to describe here, and they should provide a nice head start for writing perl code. In the examples I used:

    Operation Meaning
    <> Reads a single line from standard input. Returns the line or false if end-of-input is encountered
    chomp(...) Remove the last character from a string if that character is end-of-line
    rand(...) Returns a random number between 0 and the argument
    int(...) Returns the integer value of its argument
    use strict;
    use warnings;
    
    # Read text lines from the user until input ends.
    # If running this snippet, use Ctrl+d (on unix) or Ctrl+Z (on windows) to create end-of-input character
    while (my $line = <>) {
    # Remove end-of-line char
      chomp $line;
    # Do other things with the $line
    }
    
    # put a random number between 0 and 9 inside $rand
    my $rand = int(rand(10));
    
    # put a random number between 5 and 14 inside $large
    my $large = int(rand(10)) + 5;
    
    
course: