[Oc-pm] need help with subroutines & funtion

Ben Tilly btilly at gmail.com
Mon Sep 8 08:27:19 PDT 2008


On Mon, Sep 8, 2008 at 3:04 AM, Raul Ruiz Jr. <fast.linux at yahoo.com> wrote:
> I am taking an online ceu course in scripting with Unix. I have been stumped
> by this project. Can anyone out there help me out a bit. I created a script
> at the bottom and it does not quite work. What am I missing?
> I know I am missing some thing but this is my first time working with perl.
> I know it will take me a while to get good at it but so far its been fun.  I
> would appreciate the help if possible.

I won't give you the full answer, but I'll give you a couple of tips.

The first is that good Perl practice is to _always_ put the line:

use strict;

at the top of every file, and then declare variables when you first
use them.  Usually with "my".  You can also declare globals with use
vars or our.  The point of that is to catch many typos automatically.
(It catches a couple of other important mistakes as well, but typo
catching is the main win.)  Of course that introduces scoping.  An
old, but still good, introduction to the complexities of scoping in
Perl is http://perl.plover.com/FAQs/Namespaces.html.

That said, here is the problem that probably has you stumped.  In your
library you have:

> sub sumIt(){
>    @functionArray = @_;
>    foreach $line(@functionArray){
>    $functionSum += $line;
>    }
>    return $functionSum;
> }

Unfortunately the pair of parentheses in the function declaration is a
prototype telling Perl that this function takes no arguments.  Don't
worry about what prototypes are for, just know that prototypes are
almost always the wrong thing to do.  So change that declaration to:

sub sumIt {
    ...
}

And incorporating my scoping advice that code would become:

sub sumIt {
    my @functionArray = @_;
    my $functionSum = 0;
    foreach my $line (@functionArray) {
        $functionSum += $line;
    }
    return $functionSum;
}

Cheers,
Ben


More information about the Oc-pm mailing list