in reply to Using variable contents in new variable name

As imp points out, you really don't want to do this.
Have a read of this excellent article by Dominus to understand why not.

What you probably need instead is a hash. If you are not sure how to implement this, post a short snippet of the actual code.

Cheers,
Darren :)

  • Comment on Re: Using variable contents in new variable name

Replies are listed 'Best First'.
Re^2: Using variable contents in new variable name
by antioch (Sexton) on Dec 11, 2006 at 02:40 UTC
    Yeah, I had a feeling what I needed was a hash but like you said, I have no idea how to implement it in this situation.

    Not sure how much this snippet will help (I'm also working in Tk) but:

    ## This is the button that initiates the sub ADMISSION $COLUMN_1->Button(-image=>$admiss_1, -width=>179, -border=>0, -background=>'#c2d297', -relief=>'flat', -command=>sub{ ADMISSION('1') } ) ->pack(-side=>'top'); ## This is part of the sub ADMISSION that contains a text field ($name +field) that the variable "$admiss_?_name" needs to be assigned to.(Wi +th the question mark being replaced by the "1" being passed by the bu +tton) sub ADMISSION { $namefield->Text(-width=>30,-height=>1)->pack(); }
    So ideally, the text field in the sub would be assigned like this

    $admiss_1_name = $namefield->Text(-width=>30,-height=>1)->pack();

    Thanks for your help guys!

      Your sample line becomes:

      $admiss_ref->{name} = $namefield->Text(-width=>30,-height=>1)->pack();

      Or if, as seems to be the case, there are a number of these things in an array you could:

      $COLUMN_1->Button(, ... -command=>[\&ADMISSION, \%admiss, 1]) ->pack(-side=>'top'); ... sub ADMISSION { my ($admiss_ref, $index) = @_; $admiss_ref->[$index]{name} = ... }

      DWIM is Perl's answer to Gödel
        Thanks a lot! Helps clear some things up..

        I still don't completely understand what's going on in the sub though..

        I see that the hash %admiss and the variable "1" are being passed but I don't get how "$admiss_ref->$index{name}" ends up being "$admiss_1_name"

        Sorry if this is pushing it, but I just want to understand how this works in hope that I'll know how to incorporate more parameters to pass and be able to assign "$admiss_1_name", "$admiss_1_date", "$admiss_1_service" and so on to their appropriate text fields. (This process is being repeated for 27 others ex. $admiss_4_name, $admiss_4_date, $admiss_4_service..)

        Thanks again!!