Hi i really need a variable as hash name. But I am getting this errors. Can someone help??
#!/usr/bin/perl -w
use strict;
my %VIEW_hash = ( 'a' => 'A', 'b' => 'B', 'c' => 'C');
my $X = "VIEW";
my $name = "$X"."_hash";
foreach my $in (keys %$name){
print "$in -- $$开发者_运维问答name{$in}\n";
}
I doubt that you really need to do it this way. Most likely, you are just wanting to break the rules because you don't know a better way to do it.
Consider using a hash to store the textual links to your actual array:
my %VIEW_hash = ( 'a' => 'A', 'b' => 'B', 'c' => 'C');
my $X = "VIEW";
my $name = "$X"."_hash";
# Our new code
my %meta = ( "VIEW_hash" => \%VIEW_hash );
my $href = $meta{$name};
say @$href{"a".."c"};
say $href->{a}
I changed something but this may fit your needs.
First of all you have to use the no strict 'refs'
pragma, in order to use symbolic references. Then you have to switch from lexical variable to package variable ( defined with our
).
I choose to limit the extension of the strictures free zone to a block enclosed with curly braces: it may save you a couple of headaches in the future.
#!/usr/bin/perl -w
use strict;
{
no strict 'refs';
our %VIEW_hash = ( 'a' => 'A', 'b' => 'B', 'c' => 'C');
my $X = 'VIEW';
my $name = "$X".'_hash';
foreach ( keys %$name ) {
printf "%s -- %s\n", $_, $$name{ $_ };
}
}
精彩评论