Mercio has asked for the wisdom of the Perl Monks concerning the following question:

I am working on creating a module for experience. I am came to a standstill while trying to pass variables from one subroutine to another. I have tried many different ways but I am still stuck. This is what I have...
sub new { my $package = shift; my @fileArray = 'counter.pl'; if (@_) { my $fileArrayR = $_[0]; @fileArray = @$fileArrayR; } test(\@fileArray); totalBandwith(\@fileArray); return bless({}, $package); } sub test { my $self = shift; my $test = $_[0]; # <-- Line 53 my @tests = @$test; foreach my $line (@_) { print $line; } }
This is not what I actually want the script to be (I don't want it to print, for ex), but I am just tryint to test it. I keep getting Can't use an undefined value as an ARRAY reference at Counter.pm line 53. from the command prompt when I try to run it. Any help would be great, thanks.

Replies are listed 'Best First'.
Re: Module Help
by shemp (Deacon) on Jun 24, 2004 at 19:58 UTC
    Regardless, your problem is in how you are calling test, and probably other methods in your module.

    Unlike some other languages, when you're in an object method, you still need to explicitely have your $self used to call other methods. So if you re-write your code like this:
    sub new { my $package = shift; my @fileArray = 'counter.pl'; if (@_) { my $fileArrayR = $_[0]; @fileArray = @$fileArrayR; } my $self = {}; bless $self, $package; $self->test(\@fileArray); $self->totalBandwith(\@fileArray); return $self; }
    To call methods within the package in an OO sort of way, you do it as $self->Method(), because $self is a reference to the object instance you are working with, and $self gets (magically) unshifted onto the param list being passed in. So your method shifts off $self, and you have the rest of your param list as it was in the call.

    It is 2 very different things to call $self->Method() and Method(), i dont want to get into all the details here, but this distinction is important to understanding OO in perl.

    Now if you were indenting to call your package functions (methods) in a non-OO sense, you dont get the reference to the object, i.e. $self, so you cant shift it off. If you do, you're losing your first explicit param from the call.
Re: Module Help
by pbeckingham (Parson) on Jun 24, 2004 at 19:52 UTC

    You are accessing the first argument to test using shift, but then you access a second argument via $_[0].

    Your calling code only passes a single reference to an array, which is a single scalar, therefore the $_[0] has nothing to access. Try:

    $self->test (\@fileArray);
    Which then calls the sub as an object method, which automatically provides the $self arg.

Re: Module Help
by Mercio (Scribe) on Jun 24, 2004 at 20:08 UTC
    Thanks a million. I now got it working great. I understand what you mean now in calling methods. I was a little confused at first, but I looked it over and I get it now. Thanks a lot.