Can I pass two variables through a subroutine and if can how to grab the passed variables?

Below is the example of codes:

$test1 = "abc";
$test2 = "def";

function($test1,$test2);

sub function($){
    --What should I do here to get the `$test1` and `$test2`--
    --Is it possible?--
}

Expected Result:

Able to grab $test1 and $test2 inside the sub function by passing through the function($test1,$test2).

Thanks for the comments ,teaching and answers.

Upvotes: 0

Views: 87

Answers (1)

RobEarl
RobEarl

Reputation: 7912

Inside the subroutine the arguments will be available in @_. You can retrieve them using shift:

my $test1 = shift;
my $test2 = shift;

or by assigning @_ to a list:

my ($test1, $test2) = @_;

or by directly accessing them (any changes will also be reflected outside):

print $_[0];
print $_[1];

e.g.

function($test1,$test2);

sub function {
    my ($test1, $test2) = @_;
    # Do something with the arguments.
}

Note I've removed the prototype from function as you probably don't want it and it was only allowing one argument.

Upvotes: 4

Related Questions