Do you know where your variables are? | |
PerlMonks |
Re: Re: Array indicesby jordanh (Chaplain) |
on Sep 14, 2002 at 16:24 UTC ( [id://197884]=note: print w/replies, xml ) | Need Help?? |
I really agree with this.
"If you are good, you never need to use indices." is an over-generalization. And, you know what they say about generalizations. Generalizations are always wrong. :-) That being said, it's really pretty rare that you need to use indices in Perl. As many have pointed out, your example is not a good one. Here are a few cases where I can imagine that indices are very useful:
Most of these examples are fairly unusual. In some of them, you could probably find ways to do it without indices, but indices are the most natural way of doing it. I guess I would say that using the zeroeth element is a special case that comes up a lot and may be acceptable. In languages like C, the use of indices is more pervasive. This is because C doesn't have good high-level data structures. It's often convenient in C to maintain lists as arrays because more complicated structures will have to be garbage collected and you have to be very careful about what you do with references to such structures. You don't have those problems in Perl. So, you should try to fit your solution into high level data structures, where access via indices is unnatural, for a number of reasons. Understandability, maintainability and extensibility being a few. Array indices in Perl should be usually viewed as a low-level feature. To be used very sparingly and usually encapsulated as much as possible so that the main program logic doesn't have to deal with them. Viewed this way, most of the 0/1-based arguments become trivialized. Who cares if they are 0 or 1 based as long as they are used so rarely? Array indices are similar to goto, in many respects. Rarely necessary, but just the thing for some situations. Update: September 15, 2002 1107 EDT In reviewing some code, it's pretty clear to me that I overstated the case against indices above. I also think that it's valid to use array indices to access arguments to subroutines, to access any data returned as fixed vectors, like from local/gmtime() and the like. These might roughly fit into the category above of accessing tuples, but it's actually a lot more common than I have presented it as being. In any case, their use is still fairly limited. These cases are "read only" kind of uses, where the data is presented in a list or array and you just want to fetch specific fields.
In Section
Seekers of Perl Wisdom
|
|