Wednesday, October 19, 2022

Pass by reference example in perl

 

sub swap{ #parameters num1 and num2 passed using pass by value method

  $temp = $_[0];   #creating a variable temp and setting equal to $_[0]
  $_[0] = $_[1];  #setting the value of $_[0] equal to $_[1]
  $_[1] = $temp;  #setting the value of $_[1] equal to temp which is equal to $_[0]
}

$num1 = 4;
$num2 = 5;

# Have a careful look at this function call
print "num1 is: $num1\n";
print "num2 is: $num2\n";
print "\nAfter swapping\n\n";

swap($num1,$num2);
print "num1 is: $num1\n";
print "num2 is: $num2";

No comments:

Post a Comment