Var::Extract - Assign lexical scalar values from container types
use Var::Extract qw(vars_from_hash vars_from_getters); use Class::Struct qw(struct); my $h = { foo => "This is foo", bar => "This is bar", baz => "This is baz", }; vars_from_hash($h, my ($foo,$bar,$baz)); print "foo:$foo\nbar:$bar\nbaz:$baz\n"; # => "foo: This is foo..." struct Klass => [attr0 => '$', attr1 => '$']; my $klass = Klass->new(attr0 => 42, attr1 => '666'); vars_from_getters($klass, my ($everything, $evil)); print "Everything is $everything, evil is $evil\n"; # => "Everything is 42, evil is 666"
Ever came across something like this? my $foo = $h->{foo}; my $bar = $h->{bar}; my $bas = $h->{baz};
or something worse: my ($foo,$bar,$baz) = @{$h}{qw(foo bar baz)};
One involves a lot of boilerplate, and the other involves being a pain to modify especially with many variables. As a bonus point, you also get to type each variable name twice.
Var::Extract exports two functions on request:
Will assign values of the keys of the hash which correspond to the names of the variables passed. If a key is not found, the variable will remain undefined ( perhaps i should add a switch here to adjust this behavior, but that would mess up the calling convention).
Does the same thing as vars_from_hash, except that instead of using hash keys, it uses Class::-style accessors
An optional $prefix may be provided in the first argument, which is useful in case accessors are named as get_foo, then vars_from_getters("get_", $obj, my $foo) will be assigned the value of $obj-get_foo
vars_from_getters("get_", $obj, my $foo) will be assigned the value of $obj-
Copyright 2011 M. Nunberg for Dynamite Data This module is dual licensed as GPL (v2 or higher) and "The same license as Perl itself"
Hash::Extract, which is similar to vars_from_hash
To install Var::Extract, copy and paste the appropriate command in to your terminal.
cpanm
cpanm Var::Extract
CPAN shell
perl -MCPAN -e shell install Var::Extract
For more information on module installation, please visit the detailed CPAN module installation guide.