use strict; use warnings; use Data::Dump qw/pp dd/; $\="\n"; my @var_list; use vars (@var_list = qw/$s1 $s2 $s3 @a1 @a2 @a3/); my %hash = ( s1 => 1, s2 => 2, a1 => [1,2,3], a2 => [], ); { no strict 'refs'; for ( @var_list ) { my ($sigil,$name) = m/^([\$@])(.*)$/; #warn $name; if ($sigil eq '@') { *{$name} = exists $hash{$name} ? $hash{$name} : []; } if ($sigil eq '$') { *{$name} = exists $hash{$name} ? \ $hash{$name} : \ undef } } } # test for my $var ( @var_list) { print "--- $var"; eval "print \"\$var = <$var> isn't false\" if $var"; }
--- $s1 $s1 = <1> isn't false --- $s2 $s2 = <2> isn't false --- $s3 --- @a1 @a1 = <1 2 3> isn't false --- @a2 --- @a3
please note that many things can be false in Perl, including the value 0.
So you may rather test if (defined $scalar) and if (@array) or even better if(exists $hash{name})
I don't think this will really help you, but you may learn from the code! =)
Cheers Rolf
(addicted to the Perl Programming Language :)
Wikisyntax for the Monastery
FootballPerl is like chess, only without the dice
In reply to Re: How to create variables for each hash key that has a value.
by LanX
in thread How to create variables for each hash key that has a value.
by Perl300
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |