[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [MacPerl] Loop question



At 12:25 PM 12/5/00, Matthew Fischer wrote:
>I have a script that reads a file into an array, then prints out 
>each line of the array, then does some other stuff with the array. I 
>need to change it so it only prints out the first 8 lines of the 
>array. How would I change this to do that?
>
>
>     foreach $line (@whole) {
>       $line =~ s/\n//g;
>       print "$line\n";
>
>
>     }
>

FYI, your snippet above uses pattern matching to remove the line 
ending. It's way more efficient to use the chomp function to do this. 
You can use the following statement to remove the line ending from 
every "line" in the array:

   chomp @whole;

But then, why loop? I suppose it depends on what the "other stuff" 
you want to do is, and when you want to do it, but if you've read 
lines from a file into an array in the usual way and haven't chomped 
them, then how about:

    print $whole[0..7];

If you _have_ chomped, then:

   print join("\n", @whole[0..7]), "\n";

Guessing that you're looping to do both things (printing the first 8 
lines and "other stuff"), this might be faster:

   print $whole[0..7];
   chomp @whole;
   foreach $line (@whole) {
     #do stuff with $line
   }

Then, just in case you don't want to do _anything_ but print the 
first 8 lines, but you want to continue and do stuff with the lines 
after #8, then the foreach loop would be:

   foreach $line (@whole[8..$#whole]) {
     #do stuff with $line
   }

All of these leave @whole whole (except for the chomping).

1;



- Bruce

__Bruce_Van_Allen___Santa_Cruz_CA__

# ===== Want to unsubscribe from this list?
# ===== Send mail with body "unsubscribe" to macperl-request@macperl.org