Skip to content

A subroutine example #41

Closed Answered by Stagyrite
eltikia asked this question in Q&A
Discussion options

You must be logged in to vote

Let's consider what the handbook says, and we need both Perl 1 and Perl 5 interpreters to find out how it works.

No call-by-reference in Perl 1

A pass-by-reference example wouldn't work in Perl 1, and here is a good try.

sub trySwap {
    $temp = $_[0];
    $_[0] = $_[1];
    $_[1] = $temp;
}

$a = 1;
$b = 2;
do trySwap ($a, $b);
print $a;
print $b;

This Perl 1 program prints 12 which is different from what we expect.

Call-by-reference in Perl 5

Call-by-reference is the default Perl 5 mechanism, just like the handbook states.

sub swap {
    $temp = $_[0];
    $_[0] = $_[1];
    $_[1] = $temp;
}

$a = 1;
$b = 2;
swap ($a, $b);
print $a;
print $b;

It prints 21 just like expected.

Somethin…

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by eltikia
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants