PDA

View Full Version : passing from sub to sub - is this correct?


bazz
08-10-2008, 06:27 PM
forgetsees here :(

I am passing two vars from one sub to another. Is this the correct way?


sub one{
&totals($rooms_total,$options_total);
}

sub totals{
my ($rooms_total, $options_total) = @_;

print qq(
rooms_total = $rooms<br />
options_total = $options_total<br />
);

}



It seems to work but maybe it's buggy?

bazz

shyam
08-10-2008, 06:43 PM
looks fine :)

FishMonger
08-10-2008, 06:46 PM
That is a very common and normal approach to passing vars.

The only change I'd make would be to drop the & from the subroutine call.

KevinADC
08-10-2008, 10:26 PM
It seems to work but maybe it's buggy?

bazz

Not only is it recommended way to pass data between subroutines, its really the only way. If you find you are passing really long lists of variables or multiple lists, then you will want to pass references to the data and not the data itself.

FishMonger
08-11-2008, 08:51 AM
Actually Kevin, it's not the only way to pass the variables.

Here's an example that demonstrates a side effect of calling subs with & that you should be aware of and normally want to avoid.
#!/usr/bin/perl

use strict;
use warnings;

my $rooms_total = 500;
my $options_total = 175;

one($rooms_total, $options_total);

sub one {
&totals;
}

sub totals {

my ($rooms, $options) = @_;
print $rooms + $options;
}

KevinADC
08-11-2008, 10:11 AM
Yes, its explained in perlsub:

Subroutines may be called recursively. If a subroutine is called using the & form, the argument list is optional, and if omitted, no @_ array is set up for the subroutine: the @_ array at the time of the call is visible to subroutine instead. This is an efficiency mechanism that new users may wish to avoid.


I think you agree its not the best way to go about passing arguments to subroutines and should probably be avoided for the most part.

bazz
08-11-2008, 02:22 PM
Thanks to each of you.

I have now removed the & symbol.

bazz