[Israel.pm] Perl Advocacy

Gaal Yahas gaal at forum2.org
Wed Dec 29 10:43:55 PST 2004


david istermann wrote:
> Issac Goldstand  wrote:
> 
>>A hash table uses a hash algorithm and buckets to store the data in memory.  
>>An array is a sequential data set with records of a preset size (pointers/refs/etc 
>>have static small sizes), sitting in memory.
> 
> I know that. That's the internal implementation point of view. But
> from the point of view of the end-user (that is, the Perl programmer)
> these two data types provide almost the same functionality.
> Why 'each' is restricted to hashes, and 'foreach' to arrays only? I
> think I should be able to do both:

A hash is listified in many perl contexts. You should define what you
want out of these, but some of them are not syntax errors:

> while ( ($key, $val) = each(%myhash) ) {...}   # $key is a string
> while ( ($key, $val) = each(@myarray) ) {...}   # $key is an integer

You want $key in the second line to be the index? 1, 2, 3 etc.?

Then write the almost equivalent

      for my $key (0 .. $#myarray) {
          my $val = $myarray[$key];
          ...
      }

Or implement an iterator of your own. (If you do that, you'd be able
to add the encapsulated resettable state feature that each() has. If
you know how references work in Perl, you'll see that writing this
to accept either hashes or arrays is easy.)

> foreach $key (@myarray) {...}
> foreach $key (%myhash) {...}

Already works. Alternates keys and values. If you want just the
keys, write

      foreach my $key (keys   %myhash) { ... }

Or for the values,

      foreach my $val (values %myhash) { ... }

> and even,
> foreach ($key, $val) (@myarray) {...}
> foreach ($key, $val) (%myhash) {...}

I don't understand what you want to happen here in the array case.
And in the hash case, you already have the while each syntax. How
would this be different?

> The same way as exists() and delete() work for both data types. Won't
> it be handy? Perl has a lot of "automagic" features already - so
> determining "magically" whether an array is given it or a hash, does
> deserve it's place.

exists() and delete() work for both data types because the analogy is
clearer. It's not obvious what interpretation is the one you wanted
in your code quotes, which is an indication that different people may
want different things.

(By the way, delete for hashes and arrays is not 100% equivalent. It
can't be. delete $hash{$key}, if $key existed, is guaranteed to
shrink "keys %hash", while delete $array[$index] isn't.)

Gaal

-- 
Gaal Yahas <gaal at forum2.org>
http://gaal.livejournal.com/



More information about the Perl mailing list