We don't bite newbies here... much | |
PerlMonks |
Re: shift v. indexing into an arrayby Joost (Canon) |
on Nov 15, 2009 at 21:58 UTC ( [id://807312]=note: print w/replies, xml ) | Need Help?? |
The reason seasoned programmers avoid indexes when they can is because there are nice abstractions for many common cases that are easy to understand, make the intent of the code clearer and are more concise.
Perl's builtins include map and grep as simple examples: if you want to filter out some information in a large or small array it's clearer to use grep, if you want to transform an array into a new one, it's clearer to use map. If you want to modify the array in place, you can generally use simple for(each): for (@array) { $_ = $_+1 }. You really only want to use indexing if the index is more than just the index in your algorithm. It's also sometimes the case that using an index makes it easier to do operations on related elements in a list (though that has more to do with a lack of builtins that deal with groups of elements - you can easily write functions that handle the problem in a more generic way). My rule of thumb, inspired by more functional languages like Scheme, is this: most of the time, you want to produce a new list/array, and that entails you probably don't want to use for() with or without indexes. But when you instead want to produce side-effects (like modifying the original array, or printing each element) you do want to use for(). I try to use while(defined shift(@array)) etc only on buffers and the like that get filled in one place and are "simultaniously" drained in another, and shift() on its own pretty much only when reading function arguments. On the subject of shift() - perl arrays keep a "start-of-array" number in their datastructures, so using shift() usually doesn't move any items at all and it's generally pretty efficient to shift() even very large arrays. See Perlguts illustrated. I'm assuming shift/push combos move stuff around every once in a while, since I write code that depends on that behaviour and it seems to work, but I'm only 90% certain on that. As for where to declare variables: declare them in the smallest block you can, if only because the memory they're using can potentially be freed when the code leaves that block of code. Don't worry about potential cpu problems there unless you have serious reasons to think they're any problem in a real program. On the whole of your program's runtime they're almost always a completely trivial concern, and there are even potential optimizations to make on "locally declared" variables - though perl doesn't usually make those optimizations. Also note that looping over a lexical variable declaration does not 're-declare' that variable. It just gets marked as uninitialized.
In Section
Seekers of Perl Wisdom
|
|