in reply to While.For loop noob query

For a small file (1 to 100 lines would qualify), you can just read the whole thing into an array at the start. Then you know how many lines you have.
my @lines = <TXTIN>; for (@lines[0..($#lines - 1)]) { s/yada/yadda/; } $lines[-1] =~ s/different/substitution/;

Caution: Contents may have been coded under pressure.

Replies are listed 'Best First'.
Re^2: While.For loop noob query
by jriggs420 (Sexton) on Oct 06, 2005 at 15:05 UTC
    Hi Roy, Quick follow up if you are still in here..What is this doing?
    for (@lines[0..($#lines - 1)])
    it's kind of hard for me to see what's going on..Would you mind translating somewhat so I can adjust to my particular needs, if necessary. Thanks again
      It's going through all the elements of @lines except the last one. $#lines is the index of the last element of @lines. So 0..($#lines - 1) is therefore the range from zero to index of the next-to-last element. So @lines[0..($#lines - 1)] is a slice of all but the last element.

      Caution: Contents may have been coded under pressure.

      $#lines is the index of the last elements of the array @lines. Let's say you have 10 lines. Their indexes would be 0 through 9, so $#lines would be 9.

      @lines[ LIST ] is an array slice. It returns a list formed from the elements indexed by LIST. In our earlier example, @lines[0..($#lines - 1)] returns elements 0 through 8.

      The for here starts a foreach loop over each element of the returned list. In other words, it loops over all up the last element of @lines. Since no variable name is specified, $_ will hold the value for the current iteration.

      I think $#array and array slices are documented in perldata. Loops are documented in perlsyn.