Perl-Sensitive Sunglasses | |
PerlMonks |
Re: How to create variables for each hash key that has a value.by shmem (Chancellor) |
on Jun 26, 2019 at 23:06 UTC ( [id://11102007]=note: print w/replies, xml ) | Need Help?? |
What I am doing right now is creating fixed number of variables for all the known keys. But the number of keys sent by front end might change and I won't be able to handle that. I want to be able to create variables by checking the keys and their values. Hashes were created to avoid the creation of variables; instead of that a container is made which holds all "variables" as in a book. Perl variables - non-lexical variables, that only apply for a given scope - aren't much different in that respect, since they are identifiers stored in a symbol table which - suprise! - also is a hash. Each identifier is connected to a hash which has slots for each type: SCALAR, ARRAY, CODE, GLOB and so on.
Instead of messing with variables created from keys and possible side effects, it is much more convenient to have them easily controlled in a container. Use e.g. $v{foo} instead of $foo. This is only slightly more typing, but enables you to control passed values via an array which holds the names of the variables you request to be able to create:
The scope of the hash variable %v (in the example, go find a better name) is entirely up to you. You can make it into a lexical, a package variable at the main level, or a global (read perlvar).
perl -le'print map{pack c,($-++?1:13)+ord}split//,ESEL'
In Section
Seekers of Perl Wisdom
|
|