Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Convert string to variable

by ShermW0829 (Sexton)
on Feb 16, 2018 at 20:27 UTC ( [id://1209330]=perlquestion: print w/replies, xml ) Need Help??

ShermW0829 has asked for the wisdom of the Perl Monks concerning the following question:

Name: Sherman 71 years old retired and creating my own poker visits database

Platform: HP Compaq 6710b

Operating System: Ubuntu 17.10

PERL Version: 5.26

postgresql Version: 9.6

Problem: Need to assign a string to act as a variable

I am building a front end for postgresql entries. I have fourteen entries that I need to query the user and set the user's value into a variable. I am using IO::Prompt.

If I straight-line the code everything works. e.g:

my ($date_in, $date_out); $date_in - prompt("Start Date: "); $date_in =~ s/^\s+|\s+$//g; $date_out = prompt("$End Date: "); $date_out =~ s/^\s+|\s+$//g;

And 12 more user inputs to get along with the no space check equals 24 more lines of code. Lots of code so I tried the following:

my ($k, $date_in, $date_out); my %var_list = ('date_in'=>'Start Date', 'date_out'=>'End Date'); foreach $k (keys(%var_list)) { ## $k prints date_out and then date_in print( "\$k: \"$k\"\n" ); ## $var_list prints End Date and then Start Date print( "\$var_list{k}: \"$var_list{$k}\"\n" ); ## Below is where I want to go: ## $k = prompt($var_list{k}); ## and have $date_out = user's entry ## ## Now how do I assign a beginning $ ## to change date_out to $date_out? ## The below does not work ## ${$k} = prompt(${$var_list{k}}); ## ## I've tried $$k, $($k), and ${$k} ## An example error is the following: ## Can't use string ("date_out") as a SCALAR ## ref while "strict refs" in use at ## ./build_sql_entries line 25 }

Thank you;

Sherman

Replies are listed 'Best First'.
Re: Convert string to variable
by choroba (Cardinal) on Feb 16, 2018 at 20:37 UTC
    See Why it's stupid to `use a variable as a variable name'.

    The better way is to use a hash. You already know how to do it, just create another hash alongside %var_list (which could be better named %questions):

    my %questions = (date_in => 'Start Date', date_out => 'End Date', ); my %answers; for my $key (keys %questions) { $answers{$key} = prompt($questions{$key} . ': '); }

    Alternatively, you can store all the information in one hash:

    my %questions = (date_in => { q => 'Start Date' }, date_out => { q => 'End Date' }, ); for my $key (keys %questions) { $questions{$key}{a} = prompt($questions{$key}{q} . ': '); }

    ($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,

      MJD's "varvarname" post is a classic. I grin and smile every single time I see it, and read it through its entirety every time :) (Obviously, I use it where necessary and nobody else has posted it)

      Every single Perl hacker has experienced this through my experience. Not one of them (including me) hasn't run into wanting to do these things that I've found over the years.

      For the more experienced, it's a bit of entertainment. For the new people, it should point out the detrimental effects of how you can literally burn yourself (using safe-for-work language here).

      Thank you for raising that newsgroup thread one more time. I needed a good laugh :)

      OP... we've all been thrown that thread one time or another, so take with a grain of salt. choroba's advice is good advice.

Re: Convert string to variable
by holli (Abbot) on Feb 16, 2018 at 22:20 UTC
    Please note that the construct s/^\s+|\s+$//g; is not as clever as you might think and a possible performance drain. See this thread on StackOverflow.


    holli

    You can lead your users to water, but alas, you cannot drown them.

      For normal line length strings the difference is of the order of a few micro-seconds: nothing to bother with except in an inner loop that is executed thousands of times a second. Readability and personal aesthetics is where it is at. Personally I'd go with the single regex version, at least partly because I'm accustomed to doing it that way and so it looks natural to me. YMMV and I wouldn't be upset to see the two regex variant (on two lines).

      Premature optimization is the root of all job security
      "...this thread on StackOverflow -> asked Oct 8 '08 at 20:02"

      He, nice! It was posted 10 years ago. Your memory works well ;-) You remember I wish I could remember which posts I wrote...?

      Best regards, Karl

      «The Crux of the Biscuit is the Apostrophe»

      perl -MCrypt::CBC -E 'say Crypt::CBC->new(-key=>'kgb',-cipher=>"Blowfish")->decrypt_hex($ENV{KARL});'Help

Re: Convert string to variable
by harangzsolt33 (Chaplain) on Feb 16, 2018 at 20:35 UTC

    I am no expert, but if you have a hash such as my %var_list = ... then you can get its contents one by one by spelling out the key in brackets and quotes. At least, this works on my computer. I use Tinyperl 5.008.

    my $SOMETHING = $var_list{"date_out"};

    or something like that.

Re: Convert string to variable
by Anonymous Monk on Feb 17, 2018 at 13:30 UTC
    "The set of variable-names" is a so-called namespace. But it's a namespace upon which literally everything else depends so you never want user inputs (malicious or otherwise) to be able to create new ones or to arbitrarily access or change existing ones. That's a lesson that PHP programmers learned the hard way. (It's not so much the case anymore, but it used to be that you could achieve amazing things by tacking ?is_admin=1 to a URL-string.) Code that is written that way can never be made secure or stable.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1209330]
Approved by holli
Front-paged by haukex
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (6)
As of 2024-04-18 00:52 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found