HeHe... I was trying to "give enough info to let acid 'take and run further' with it" - so now that the cat's out of the bag, so to speak, here's a couple small fixes as well... (no offense/etc to smirc... he posted some really good stuff)
Quote:
Originally posted here by smirc
Here's what I would do:
Code:
my($i) = 0;
my($file) = "readme.txt";
open(INFO, $file) || die "Error opening $file.";
while (<INFO>) {
printf("%.6d: %s\n", $i, $_);
$i++;
}
close(INFO);
The open, technically, should explicitely declare how the file's to be opened and indicate the problem if the open fails... in this case, just read the file rather than trying to open a pipe or similiar:
Code:
open( INFO, "< ${file}" ) || die( "Can't open file \"$file\" - Error was \"$!\" );
The while loop will have a small problem with the EOL characters in a multi-line file... should probably trim those, as well...
Code:
while( <INFO> ){
chomp( $_ );
printf("%.6d: %s\n", $i, $_);
$i++
}
Technically, to limit the lines, the increment operator can be thrown in to the print statement, but I think that starts to cross the line on readability versus functionality.
Quote:
Things to note:
1.) Always use "my" to define the scope of your variables. You should be using "use strict;" anyway.
perl -w is also a good one to get in the habit of using.
Quote:
2.) Always check that your file open has worked.
I'd expand that to "always check that something unexpected hasn't happened when depending on externally influenced data. Just because your web for says "only accept a five-digit number" it doesn't mean some smart-a** won't try to feed you some other unexpected info another way.
Quote:
3.) Using a while eliminate the need to use an array and is generally a better way of reading the file. @lines = <INFO>; is not a good way of doing this.
The array method here is "expensive." For a suitably large file, it can kill the process/machine. Reading the file iteratively and discarding things after you are done with them is much kinder.
Quote:
4.) printf will let you print place markers so that the columns for the source print out all line up verticaly. Looks nicer.
The caveat here is that print formatting is slow. It's great to use when you need it, but it's better to use "print" when you can get away with it. Abuse of "printf" will slow a routine down to the point that you can see it (I used to do everything using printf's); use it sparingly and you're fine.