The Ghost wrote:
my %hash = (
    foo => 'bar'
    );
my $name='hash';
my $key='foo';

print $name{$key};

how can I get that to print "bar"?

You can't, given the way you've set up %hash and $name. You're trying to take a "soft" reference to a lexical variable, which won't work.

(well, you could so something extremely cheesy like:

   print "key=", eval "\$$name\{$key}";

but yecch, don't to that)

You can do this:

   use strict;
   my %hash = ( foo => 'bar' );
   my $name = \%hash;
   my $key = 'foo';
   print $name->{$key};

Or you could do this (but don't!):

   use strict;
   our %hash = ( foo => 'bar' );
   my $name = 'hash';
   my $key = 'foo';
   no strict 'refs';
   print $name->{$key};

Usually, if you're trying to use a string (perhaps coming from the outside world) as a symbol name, you're better off using a hash instead:

   my %data = (
       'hash1' => { foo => 'bar' },
       'hash2' => { foo => 'qux' },
   );

   for my $name (qw(hash1 hash2)) {
      print $data{$name}{foo};
   }

If the string isn't coming from the outside world and you just need a reference, use a proper reference (\%hash)

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to