develooper Front page | perl.fwp | Postings from November 2007

Re: fun with hashes!

Thread Previous | Thread Next
From:
Steve Fink
Date:
November 24, 2007 17:51
Subject:
Re: fun with hashes!
Message ID:
7d7f2e8c0711241245i55c4c361u259b0162c5e7e84e@mail.gmail.com
I don't think this has been mentioned, although it's really just a
combination of two existing ones: I often have a table of sets.

  for my $user (@filenames) {
    open(my $fh, "<", $user) {
      while(<$fh>) {
        $use{$user}{$1} = 1 while /include\s*['"](.*?)['"]/g;
    }
  }

It's a full graph, with fast looking and iteration over outgoing edges.

The quick existence lookup is nice while building it, but if you don't
care about that, then it's cleaner to encode it as a map from node to
array ref of children:

  $children{A} = [ 'B', 'C', 'D' ];
  $children{C} = [ 'E', 'F' ];
  ...etc...

There's sort of another use buried in there, too: hashes can be used
to map object identifiers to their data (a la inside-out objects or
something simpler that is just trying to keep the real data in a
canonical place, perhaps to avoid worrying about cyclic references.)

For an obscure and rather unsafe usage, you could use hashes for randomization:

  my @quiz_questions = ...;
  my %quiz_table;
  @quiz_table{@quiz_questions} = ();
  my ($random_first_question) = keys %quiz_table;
  while my $question (keys %quiz_table) {
     print "QUESTION: $question ";
     my $answer = <STDIN>;
     ...;
  }

Hashes can be used for caches or memoization:

  our $answer;
  sub func {
    return $answer ||= ...compute...;
  }

Hashes can be used for sparse arrays:

  $arr{10} = "X";
  $arr{83719} = "Y";

Hashes can be used for symbol tables. :-)

Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About