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).
There is a difference between "for" and "foreach", but it really doesn't matter in this example.#!/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"; }
In reply to Re: catastrophic near misses in Perl
by Marshall
in thread catastrophic near misses in Perl
by morgon
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |