Using shift
within eval
string that's inside a sub
isn't working:
Example 1 (using eval
):
grab_variable($variable1,$variable2,$variable3);
print $variable1.$variable2.$variable3; #should print: 123
sub grab_variable {
my $number_of_parameters = @_;
my $command1;
my $command2;
for (my $i = 1; $i <= $number_of_parameters; $i++) {
$command1.= "\$RefVariable".$i." = \\shift;\n";
#Generates string like:
#$RefVariable1 = \shift;
#$RefVariable2 = \shift;
#...
}
eval $command1;
for (my $i = 1; $i <= $number_of_parameters; $i++) {
$command2.= "\$\{\$RefVariable".$i."\} = ".$i.";\n";
#Generates string like:
#${$RefVariable1} = 1;
#${$RefVariable2} = 2;
#...
}
eval $command2;
}
Example 2 (direct code):
grab_variable($variable1,$variable2,$variable3);
print $variable1.$variable2.$variable3; #Prints: 123
sub grab_variable {
$RefVariable1 = \shift;
$RefVariable2 = \shift;
$RefVariable3 = \shift;
${$RefVariable1} = 1;
${$RefVariable2} = 2;
${$RefVariable3} = 3;
}
Example 1 is dynamic and achieves a solution to my real (not simplified) problem. How could I make \shift
work within the eval
code string?
Specifically, I'm trying to make a function (subroutine) that accepts any number of variables (as arguments) and get passed as references (not values) because it should modify them.