CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
passing multiple variables to sub routine

 



kind1
Deleted

Feb 19, 2000, 12:11 PM

Post #1 of 6 (433 views)
passing multiple variables to sub routine Can't Post

Ok, simple perl question:
How do you pass multiple variables to a sub routine?

I know how to pass single variables:


&subroutine($passedvariable);

sub subroutine {
my $received = shift;
}

but how do you pass more than one? I tried the intuitive solution:
&subroutine ($passed1, $passed2);
sub subroutine {
my ($received1, $received2) = shift;
}

but that only receives the first variable.

Please explain how to do this or point me to a resource that does.

Thanks-
kind1


Cure
User

Feb 19, 2000, 12:57 PM

Post #2 of 6 (433 views)
Re: passing multiple variables to sub routine [In reply to] Can't Post

Hi

&subroutine($passedvariable);

sub subroutine {
my $received = @_;
}


&subroutine ($passed1, $passed2);
sub subroutine {
my ($received1, $received2) = @_;
}


@_ its a special array to pass info to a subroutine.

Cure


japhy
Enthusiast

Feb 21, 2000, 2:41 PM

Post #3 of 6 (433 views)
Re: passing multiple variables to sub routine [In reply to] Can't Post

Watch your contexts there, cure.

<BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR>


sub foo {
my $a = @_; # $a is the SIZE of @_
my ($b) = @_; # $b is the first element
}
</pre><HR></BLOCKQUOTE>

shift() just returns (and removes) the first element of the array.


ljfaraci
Deleted

Feb 22, 2000, 11:46 AM

Post #4 of 6 (433 views)
Re: passing multiple variables to sub routine [In reply to] Can't Post

Just a quick question,
I use the following for handling parameter passing in all my subroutines:

&subfoo ($var1, $var2, ... $varn);


sub subfoo
{ my @args = @_;

$somevar1 = @args (0);
$somevarn = @args (n);
}

Does this go against general perl programming conventions?



ljfaraci
Deleted

Feb 22, 2000, 12:06 PM

Post #5 of 6 (433 views)
Re: passing multiple variables to sub routine [In reply to] Can't Post

Correction:

sub subfoo
{ my @args = @_;

$somevar1 = @args [0]; # brackets vs
$somevarn = @args [n]; # parenthesis
}


japhy
Enthusiast

Feb 22, 2000, 1:08 PM

Post #6 of 6 (433 views)
Re: passing multiple variables to sub routine [In reply to] Can't Post

When getting elements from an array, you use brackets. Parentheses would cause a syntax error.

<BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR>


$one_value = $array[2];
($two,$values) = @array[1,4];
</pre><HR></BLOCKQUOTE>

Read the perldata documentation on this web site.

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives