in reply to Search Engine Output needs sorting

for (my $j=0; $j <= @grammatches; $j++) { ## Could be normal $j++ if u +se another variable instead of @matches for both ... for (my $l=0; $l <= @headmatches; $l++) { ... for (my $m=0; $m <= @sentmatches; $m++) {

You have an off-by-one error on your for loops, you are trying to access one element past the end the arrays.    Those are usually written as:

for my $j ( 0 .. $#grammatches ) { ## Could be normal $j++ if use anot +her variable instead of @matches for both ... for my $l ( 0 .. $#headmatches ) { ... for my $m ( 0 .. $#sentmatches ) {

Replies are listed 'Best First'.
Re^2: Search Engine Output needs sorting
by Anonymous Monk on May 28, 2011 at 13:04 UTC

    Thanks for the insightful tip! However I'm not sure what that changes, since it was working before. Did I over compensate using the 'defined' function (which I used when I saw the uninitialized error)? <\p>

    I haven't encountered the $# before, does @ not work? Thanks again!

      Using @array in scalar context gives the number of elements in the array whereas $#array gives the index of the last element.

      knoppix@Microknoppix:~$ perl -E ' > @array = ( 1 .. 5 ); > say qq{@array}; > say scalar @array; > say $#array;' 1 2 3 4 5 5 4 knoppix@Microknoppix:~$

      I hope this is helpful.

      Cheers,

      JohnGG

        Thanks for clear explanation. Does ^# give the index of the first element? Don't why you'd need it, just curious.

        Reply didn't work... Does ^# give first index? Don't know why you'd need, but curious.

Re^2: Search Engine Output needs sorting
by Anonymous Monk on May 28, 2011 at 18:09 UTC

    Wait! Is that true for all for loops in Perl? You can never use the C-style method? I always have to use foreach or that .. operator instead?

      You can never use the C-style method?

      I would not say never use -- there are instances where it might make better sense*. However, for simple (i=0;i<max;i++)-type loops, Perl has a different method of specifying it: for my $i (0..$max-1).

      This is a question of style and understanding. Just as not knowing idiomatic expressions (or using them incorrectly) can tag someone as "not from 'round here", using the C-style for loop in the general case may cause some to question how well you know Perl -- right or wrong.

      On the other hand (and this may be heresy), if you are in a C shop, and your coding standards are written from a C point of view, I suppose that could be an argument for using the C-style for loop. Not necessarily a good argument, but an argument.

      * - perhaps a time that you would want to use a C-style loop is if the increment is something other than 1, or if the exit test is something other than a simple comparison. However, this could be possibly written better in a different construct (while, for example).

      --MidLifeXis