in reply to Counting incidents of names in a file

Ask yourself this:

How can I keep track of unique "keys" using a native perl data structure?

%IthinkYouKnowTheAnswer;

  • Comment on Re: Counting incidents of names in a file

Replies are listed 'Best First'.
Re: Re: Counting incidents of names in a file
by Bishma (Beadle) on Feb 13, 2002 at 05:02 UTC
    Yeah, but I really don't like hashes. I like to keep my data in the order I want it to be in. It's a completely irrational and unfounded prejudice, I know, but it's still there.
      That's like saying I like Carpentry but I don't like drills. Then you spend your time trying to bore a hole with your screwdriver, the cabinet takes for ever to build and it's not all that sturdy.
      Or, I'm going to write a novel, but I'm not going to use adjectives.
      Hashes are one of the basic tools of the language. You wouldn't code a large C project without pointers, would you?
      Problems that would be innefficient using arrays like existance checks and counting occurances are quick and painless with hashes. And order is as simple as:
      foreach (sort keys %hash) { my $item = $hash{$_}; ... }
      Not much worse than:
      foreach my $item (@array) { ... }
      Plus there is no effort involved in inserting and delete and maintaining order.
      I usually judge the progress of junior perl programmers by their use of hashes. When they stop trying to use arrays to do the job of a hash, they've leveled up in perl. (BTW, regexp are the second tier, then map/grep)
      Of course this is all just my opinion,

      -pete
      Entropy is not what is used to be.

      If your concern is just in keeping the names in the same order in which they're seen, there are two approaches. The easiest is to look into Tie::IxHash. This is a variant of the hash that preserves the order of keys as they are inserted.

      The second way, that doesn't require installing a new module, is to have your loop also push all newly-discovered names onto an array, then use the array to iterate over the hash rather than the keys keyword.

      Don't be so quick to dismiss the basic constructs that Perl provides. They are here for a reason, and when you ask a very basic question you have to expect that your initial answers are going to be pointers to the these basic elements. At the very least, if you are going to ask such a basic question then you should state up front why you don't want to use the basic solution.

      --rjray