[EMAIL PROTECTED] wrote:
Wow, this is quite interesting! Actually, the while was not segfaulting because I had printf's in there just to make sure and they all printed fine. Now as far as the strtok() thing is concerned, that was the problem, as you said. This is interesting because I have, in the past, used strtok() this way and it has worked. So I don't know why this does not work now. In any case, my problem is solved.


Aaah - my diagnosis was a little bit off, methinks.

The problem probably arose because you pushed a value onto the array *after* the last call to 'pch = strtok(NULL, " ");'.

You'll note that in my rewrite, nothing gets pushed onto the stack after the last call to 'pch = strtok(NULL, " ");'.

ie the problem is not with the *first* value that gets pushed onto the array - but with the *last* value. This goes some way to explaining why there was no problem in the past with your usage of strtok() - there was probably nothing wrong with it.

The following (minimal) rewrite of your script seems to confirm this.

 void print_words(SV* sentence) {
        AV* mywords;
        char *sent, *pch;
        int i;
        SV* myword;
        SV** tmp;

        sent = SvPV_nolen(sentence);
        mywords = newAV();

        pch = strtok(sent," ");
        myword = newSVpvn(pch, strlen(pch));
        SvPOK_on(myword);
        av_push(mywords, myword);

        while (pch) {
                pch = strtok(NULL, " ");
                /* Do only if pch != NULL */
                if(pch != NULL) {
                  myword = newSVpvn(pch, strlen(pch));
                  SvPOK_on(myword);
                  av_push(mywords, myword);
                  }
        }

        /* s/</<=/ */
        for(i=0;i<=av_len(mywords);i++) {
                tmp = av_fetch(mywords, i, 0);
                printf("%s\n", SvPV_nolen(*tmp));
        }
}

Cheers,
Rob



Reply via email to