in reply to How to create variables for each hash key that has a value.
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.
use vars qw($foo); $foo = "bar"; # assign the value 'bar' to variable $foo ( +package global) print "$foo\n"; # prints bar print "${*foo{SCALAR}}\n"; # also prints bar! same variable ${*foo{SCALAR}} = 'quux'; # assign a different value print "$foo\n"; # prints 'quux', value has beeen changed
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:
my @known_params = qw(foo bar baz); # of these you know # this is a mockup of the passedParameters hash my %passedParameters = ( foo => 'oil', bar => 'lantern', baz => 'match', quux => 'half pig', ); my %v = validateParams(%passedParameters); print "valid parameters are:\n"; print "$_ => $v{$_}\n" for keys %v; sub validateParams { my %args = @_; my %valid; for my $key (@known_params) { $valid{$key} = delete $args{$key}; # remove from input } if (keys %args) { # any keys left which we don't know? for my $key (keys %args) { warn "unknown parameter '$key' passed, value = '$args{$key +}'\n"; } } return %valid; } __END__ unknown parameter 'quux' passed, value = 'half pig' valid parameters are: baz => match foo => oil bar => lantern
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).
|
|---|