PBP: 068 Unnecessary Subscripting

The Best Practice suggests avoiding subscripting arrays or hashes within loops.  They have a good reason too!

The reason given is that each time you have to index an array, you have to access that item in the hash or array, which is slower than simply using the iterator variable.  This is true.

Most of the examples even read more clearly than the index-every-time version, so are a double-win.

I admit, I forget about ‘values’, and often find I need the key with the value, which means iterating by keys.

2 Responses to “PBP: 068 Unnecessary Subscripting”

  1. Shawn H Corey says:

    If you need keys and values, consider using `each`. See `perldoc -f each`, http://perldoc.perl.org/functions/each.html

    • Laufeyjarson says:

      I thought the PBP suggested avoiding ‘each’, but I can’t find it now, so maybe it isn’t in there.

      I do avoid each, because it can cause action at a distance in the wrong situation. The each function stores it’s position in an internal value in the hash. There’s only one for each hash. If you’re in a loop using each, and you (or, more likely, a function you call) calls each, keys, or values on that hash the position used by each will be reset, and cause your first loop to do unexpected things.

Leave a Reply