Forum Moderators: coopster & phranque

Message Too Old, No Replies

Can I pass variables to a perl subroutine this way

         

Donboy

5:51 pm on Apr 5, 2003 (gmt 0)

10+ Year Member



Can I pass varaibles to a subroutine this way? I tried, but it didn't seem to work. Any advice on what I'm doing wrong, or is this even possible. Right now, I'm using the shift method as the first couple of lines in my sub to collect the variables. But I've been reading about how Javascript and PHP can do this, so surely Perl can too?

$Var1 = "item1";
$Var2 = "item2";
$Var3 = "item3";

print "Content-type: text/html\n\n";

&MySub($Var1,$Var2,$Var3);

sub MySub($something, $something2, $something3) {
print "Test! $something <p> $something2 <p> $something3";
}

ShawnR

1:47 am on Apr 6, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You can pass the variables in that way, (i.e. MySub($Var1,$Var2,$Var3); is OK (Don't need the & ) ) but you can't declare the variables that way in the function. Rather use:

sub MySub {
print "Test! $_[0] <p> $_[1] <p> $_[2]";
}

You can include a prototype to define the types and amounts of variables it can take, but you can't name them. For example:

sub MySub (\$\$\$){
print "Test! $_[0] <p> $_[1] <p> $_[2]";
}

($ instead of \$ will cast the arguments to scalors rather than throw an exception if the function is called with the wrong argument type.)

Shawn

andreasfriedrich

11:48 am on Apr 6, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Perl [perl.com] uses a more flexible approach to passing variables than PHP [php.net]. All parameter passed to a function are accessible via the @_ array. To assign single values to variables you can use either the shift [perldoc.com] method or assign the @_ array to a list of variables like so:


($var1, $var2, $var3) = @_;

With PHP [php.net] you can use the func_get_args [php.net] function to get an array of passed variable as well. func_get_arg [php.net](arg_number) will return the argument at the arg_number th offset of the argument list. This is similar to Perl [perl.com]īs $_[arg_number].

Andreas