in reply to Using aliases in for loops or not?

There's an old adage -- a good programmer can write FORTRAN in any language. You are programming assembley in perl, which is just silly. One of the basic bits of the Perl attitude is that you shouldn't worry about the little things, and that programmer time is a lot more valueable then CPU time, bytes in RAM, or bytes on disk. Using the implicit $_ is often trading a very little bit of CPU time for a lot of programmer time, spent looking on in confusion at code that makes little sense.

The other problem is that you are witing a slice that will always get only a single element. That's a big innefficency, and one perl would warn you about had you begun your script with use warnings;. There is a temptation to leave this out that I suspect you will feel -- the temptation to say "but I'm writing what I meant! It's valid code! Perl doesn't know better then me!". While it is true for some people that perl does not know better then you, in many cases, it really does, especially when one is starting out.

The best way to write a piece of code is generally the way that fits the way you think about it. If you think "print the first element of each array referenced from @$data", print $_->[0] foreach @$data;. If you think "loop over @$data, and print out the first element of each array it references",

foreach ($@data) { print $_->[0]; }
. On the third hand, if there was more stuff in there, then you have little choice but to use the second form, and if there's more then a couple lines, use an explicit loop variable. It /may/ be /slighty/ less efficent, but it's much easier to read.


Warning: Unless otherwise stated, code is untested. Do not use without understanding. Code is posted in the hopes it is useful, but without warranty. All copyrights are relinquished into the public domain unless otherwise stated. I am not an angel. I am capable of error, and err on a fairly regular basis. If I made a mistake, please let me know (such as by replying to this node).

Replies are listed 'Best First'.
Re^2: Using aliases in for loops or not?
by Animator (Hermit) on Feb 17, 2005 at 12:03 UTC

    I wonder if it really is an array slice...

    printing @x[0] will create a warning because an array slice is used. @$x[0] will not...

    On the other hand, @$x[0, 1] will return two elements what suggest that it is indeed an array slice...