[pm-h] Good use of hashes for our more junior members

B. Estrade estrabd at gmail.com
Thu Nov 21 06:25:27 PST 2013


Thank you, Wade.

I tend to use hashes as a "go to" way to trade time complexity for memory,
taking advantage of the "O(1)" look up the hash provides.

For example, if I have a complex data structure that will require some
iterating to get various bits of information, I will store it in 2 or more
ways that provide the look up in more efficient ways. I guess it'd be like
a poor man's heap structure. There is overhead in maintaining more than one
version of a data object, but if you're needing to optimize for speed and
can spare the memory, this is a legitimate thing to do.

Another way I will use a hash is to replace a longish if/elsif/else block
with a hash based dispatch table.  This eliminate the need for any
conditional chaining and allows the proper subroutine of code (that would
otherwise be branched into if a condition was met) to be executed
immediately. Not only is this much more efficient (O(1) branching versus
O(n), where n is the number of conditionals to test), but is makes for much
cleaner and easier to read code.

In general, hashes in Perl (due to the fact that the key can point to
literally anything) are a really nice tools not just for creating complex
data structures, but for optimizing your code on a fairly high level.

Brett


On Thu, Nov 21, 2013 at 8:13 AM, G. Wade Johnson <gwadej at anomaly.org> wrote:

> I know that everyone who has been programming in Perl for a while will
> be aware of this, but some of our members may not have done this.
>
> http://perlmaven.com/count-words-in-text-using-perl
>
> Gabor does a good job of setting up a simple problem and explaining it
> well. I have used variations of this code more times than I can count.
>
> He really does not go into using regular expressions to extract other
> things besides just words (e.g. IP addresses, telephone numbers), which
> is fine because he is focusing on the counting technique.
>
> There are also a number of things you can do with this hash when you
> are finished. The reports he shows are pretty straight-forward, but
> graphing the output is not incredibly hard if that's what you need.
>
> G. Wade
> --
> DON'T PANIC! I'm a trained professional, and far more qualified to
> panic in this situation than you are.
> _______________________________________________
> Houston mailing list
> Houston at pm.org
> http://mail.pm.org/mailman/listinfo/houston
> Website: http://houston.pm.org/
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.pm.org/mailman/private/houston/attachments/20131121/4482ff40/attachment.html>


More information about the Houston mailing list