Please Help, Perl Subroutines!

Discussion in 'Programming' started by gobbly2100, May 8, 2008.

  1. #1
    Hey,

    I am learning Perl but I just cannot quite understand how the subroutines (Functions) work in Perl

    Here are some examples of a script and if someone could explain it line by line and how it is doing what it is then I would really appreciate it

    use strict;
    sub HowdyEveryone {
       my($name1, $name2) = @_;
       return "Hello $name1 and $name2.\n" .
              "Where do you want to go with Perl today?\n";
    }
    print &HowdyEveryone("bart", "lisa");
    Code (markup):
    Source: http://www.faqs.org/docs/pperl/pickingUpPerl_8.html

    Thanks in advance!
     
    gobbly2100, May 8, 2008 IP
  2. misja

    misja Active Member

    Messages:
    61
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    95
    #2
    Ok, I will try to explain:

    use strict;
    PHP:
    Tells PERL to check if every variable is defined before it is used. If you just start using a variable without declaring it with "my", the script will crash.


    
    print &HowdyEveryone("bart", "lisa");
    
    PHP:
    This is first real line that is executed. It tells PERL to call the function HowdyEveryone with 2 parameters "bart" and "lisa" and print the result to the screen.

    
    sub HowdyEveryone {
       my($name1, $name2) = @_;
       return "Hello $name1 and $name2.\n" .
              "Where do you want to go with Perl today?\n";
    }
    
    PHP:
    This is the subroutine. "@_" is an array with the 2 variables "bart" and "lisa", ($name1, $name2) is also an array because of the brackets (). "bart" becomes $name1, "lisa" $name2. Other ways to do the same:
    
    my $name1 = shift;
    my $name2 = shift;
    
    PHP:
    The effect is the same. "shift" shifts the elements in the array @_
    or:
    
    my $name1 = $_[0];
    my $name2 = $_[1];
    
    PHP:
    The next 2 lines return a text with the 2 variables. "return" always ends the function. The text is printed to the screen because of the "print" statement outside the function.
     
    misja, May 9, 2008 IP
  3. gobbly2100

    gobbly2100 Banned

    Messages:
    906
    Likes Received:
    11
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Ah ok, that makes much more sense to me now, I think am almost there, just one other question though.

    What is the using "my" about in the subroutine?

    I don't understand what it is and what it does there.

    Thank you for your explanation, much appreciated!
     
    gobbly2100, May 10, 2008 IP
  4. milesbparty

    milesbparty Peon

    Messages:
    148
    Likes Received:
    7
    Best Answers:
    0
    Trophy Points:
    0
    #4
    The "my" keyword changes the scope of a variable. Using it inside the function makes the variable local to the subroutine.
     
    milesbparty, May 10, 2008 IP