in reply to catastrophic near misses in Perl

I am also flummoxed as to what you want. In your example, you started with what looked like "non-idiomatic" code at first glance that became even worse code. There are lots of ways to write bad code. I don't see how a thousand examples of that would be helpful.

Also I would say that the very most important thing that was wrong with this code is lack of "use warnings;", either by explicit "use warnings;" statement or on sheebang line: #!/usr/bin/perl -w. Many Windows users don't understand that the Windows ports of Perl will use the -w option on this line EVEN THOUGH the /usr/bin/perl part is meaningless!

Had you enabled warnings, your code shows a run time error with the print statement, "use of uninitialized value". This would be true even if not printing, but rather just looping and trying to do something with the values in @a. Now Perl tries to keep running and you will get untold numbers of this print line. But this is actually a feature, not a defect in Perl. Run time warnings do slow the code down a small bit, but this penalty is almost always worth it!

A super common error in programming is "off-by-one". Proper Perl coding greatly reduces this chance!

Simple re-coding to not use $i as an index...
It is actually very seldom that our FORTRAN buddies: i,j,k,l,m,n are needed in Perl! (for the young folks, i-n are first 2 letters of integer and the use of these as short term looping integers pre-dates C).

#!/usr/bin/perl -w use strict; my @a=(1..100); for my $num (@a) #foreach my $num (@a) is also just fine { print "$num\n"; } my $b=[1..100]; foreach my $num (@$b) { print "$num\n"; }
There is a difference between "for" and "foreach", but it really doesn't matter in this example.

Replies are listed 'Best First'.
Re^2: catastrophic near misses in Perl
by FunkyMonk (Bishop) on Apr 18, 2009 at 10:58 UTC
    There is a difference between "for" and "foreach", but it really doesn't matter in this example

    Care to elaborate? perlsyn#foreach says

    The "foreach" keyword is actually a synonym for the "for" keyword, so you can use "foreach" for readability or "for" for brevity.