On 04/30/2013 12:07 PM, Piyush Verma wrote:
Hi,

I want to use string as a variable name, please explain if there is any way
in perl.

Yes, there is a way. It is almost always a better idea to NOT do it that way, but to refactor your code to not require using a string as a variable name.

Please have a look on below cases, I want to implement case 2.

e.g.
Case 1: if I am using global varibale without strict module
            $var = "this";
            $this = "realvalue";
            print ${$var};

            OUTPUT: realvalue
Case 2: if I am using strict module and my variables
            use strict;
            my $var = "this";
            my $this = "realvalue";
            print ${$var};

            OUTPUT: Can't use string ("this") as a SCALAR ref while "strict
refs" in use at 2.pl line 6.


the solution to allow you to do this bad thing, that you ought not do, is two-fold: First your variable that you want to reference by name must not be a lexical-variable, so you can't declare it with "my" but instead, the simplest way is with "our" (there are other ways -- an explicit package name, or perhaps with a "use vars ... " pragma).

Second: You need to tell the compiler that you WILL be using refs, with a "no strict 'refs'" pragma.

If your heart is set on doing this, at least limit the damage by using the smallest scope possible for your non-strict refs: The following code works. Notice that I created a scope to hold the relaxation of stricture.

        use strict;
        my $var = "this";
        our $this = "realvalue";

        {
          no strict 'refs';
          print ${$var};
        }

The USUAL better solution that using variable-names in variables is to use a better data-structure than "a gathering of variables", often a hash.


--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to