Omar Omar - 1 year ago 50
Perl Question

\shift isn't working within eval string

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?

Answer Source

shift does not return the variable that was passed, it returns a copy of its value. To do what you want, you need to explicitly access @_, making code to eval like:

$RefVariable1 = \$_[0];
$RefVariable2 = \$_[1];
...

You should also end $command1 and $command2 with 1; and test that your evals succeed (eval $command1 or die "whoops: $@").

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download