[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [MacPerl] Foreach, Hash name from <>



At 08.04 -0500 1999.02.13, VIncent Nonnenmacher wrote:
>> # Grab the hash's name
>> print 'Hash to display (no "%" please): ';
>> $hashname = <>;
>> chomp $hashname;
>>
>> # Display the key:value pairs
>>
>> print 'Following is the contents of the hash %',$hashname,"\n";
>>
>> foreach $hashkey (keys(%$hashname)) {
>> print "key: $hashkey, value: $hashname{$hashkey}\n";
>> }

>$hashname is a reference to the associative array not the array itself
>try to dereference it using the $$ref or $ref-> syntax
>
>you should write :
>
>foreach $hashkey (keys %$hashname ) {
>print "key: $hashkey, value: $$hashname{$hashkey}\n";
>
>or
>foreach $hashkey (keys %$hashname ) {
>print "key: $hashkey, value: $hashname->{$hashkey}\n";

Well, but this is considered bad programming practice in general.  Good
programming practice in Perl usually involves "use strict", which would in
this case produce a warning like:

# Can't use string ("hashname") as a HASH ref while "strict refs" in use.


Usually, it is best to have a hash of hashes, so $hashname is not used a
symbol, but as an element of the hash:

#!perl -w
use strict;
my $hashname = 'hash1';
my %myhashes = (
  hash1 => {0..5},
  hash2 => {6..11}
);

my $hash = $myhashes{$hashname};
foreach my $key (keys %{$hash}) {
  print "key: $key, value: $hash->{$key}\n";
}

--
Chris Nandor          mailto:pudge@pobox.com         http://pudge.net/
%PGPKey = ('B76E72AD', [1024, '0824090B CE73CA10  1FF77F13 8180B6B6'])

***** Want to unsubscribe from this list?
***** Send mail with body "unsubscribe" to mac-perl-request@iis.ee.ethz.ch