Thursday, May 29, 2008

Perl: Invoke variable using other variable

At my last post I have mentioned how to invoke a Perl function using a variable. Today i'm going to tell how to invoke a variable using other variable. For example below example.
## Initially
$variable = "Before";
print "$variable\n";

## Take the variable name into another
$variable_name = "variable";
## Invoking the value using other variable
${$variable_name} = "Now";
print "$variable\n";
If you need to use array invoke using a variable, then below code example.
## Initially the array
@variable = qw( Before After);
print "@variable\n";

## Take the array name into another variable
$variable_name = "variable";
## Invoking the array using other variable
@{$variable_name} = qw(All have changed);
print "@variable\n";
Infact you can use Hash also for this purpose. But remember as I told you that this example doesn't work when strict is used. May be there is a way for strict, but I don't know.

1 comment:

Randal L. Schwartz said...

This is definitely considered bad form. Don't ever consider using this in production code. You will be laughed at. Cute trick, no real application.

Get function name programaticaly - Python

This little piece of code will help you to get the function name programatically. This is very helpful when you are implementing the debug...