Ilan Kleiman
Ilan Kleiman

Reputation: 1209

How to pass variables into a 'sub' block?

How can I pass on a variable into a Perl sub block?

(This is a perl CGI page.)

The variable $yellow is not passed onto the sub login block... I read somewhere that it's not supposed to, though it can be done. How can I pass the variable onto the sub block?

For example:

    $cgi = new CGI;
    $yellow = $cgi->param("yellow");

sub login {
### code .....
$yellow .....
### code....
}

Upvotes: 0

Views: 139

Answers (2)

Borodin
Borodin

Reputation: 126722

You seem to be very unfamiliar with Perl. I suggest that a quick look at the documentation would have served you better, but here goes.

There is no Perl 'sub' block. Perl has subroutines like most other languages (although they may want to call them functions or perhaps methods).

A Perl subroutine accepts an array of arguments from the built-in array called @_. You could access it directly, but it is usually best if you leave it alone and copy its contents to scalar variables local to the subroutine.

In your case, my guess is that you should write something like

my $cgi = CGI->new;
my $colour = $cgi->param('yellow');

login($colour);

sub login {
  my ($colour) = @_;

  # code using passed $colour
}

Upvotes: 2

matt forsythe
matt forsythe

Reputation: 3912

You need to code the login function to take a parameter:

sub login {
    my($arg1) = @_;
    ...
}

And then when you call the function, just pass the parameter:

login($yellow);

Upvotes: 3

Related Questions