in reply to Find Comma in a string

perldoc -f index

index STR,SUBSTR,POSITION
index STR,SUBSTR
The index function searches for one string within another, but without the wildcard-like behavior of a full regular-expression pattern match. It returns the position of the first occurrence of SUBSTR in STR at or after POSITION. If POSITION is omitted, starts searching from the beginning of the string. The return value is based at 0 (or whatever you've set the $[ variable to--but don't do that). If the substring is not found, returns one less than the base, ordinarily "-1".

$> perl -e "\$pos = -1;print (\$pos . ' ') while((\$pos = index('joe,is,at,home', ',', \$pos+1)) != -1);" 3 6 9

Edit:fixed pos init-value

regards,
tomte


Hlade's Law:

If you have a difficult task, give it to a lazy person --
they will find an easier way to do it.

Replies are listed 'Best First'.
Re: Re: Find Comma in a string
by jsprat (Curate) on Jun 25, 2003 at 18:02 UTC
    ++tomte for a good answer.

    I'd change the example a little. The quoting style used makes this one-liner hard to read - it forces backlashes where they aren't expected. With a *nix shell, single quotes won't force you to escape the dollar signs, ie:

    $> perl -e '$pos = 0;print ($pos . " ") while(($pos = index("joe,is,at,home", ",", $pos+1)) != -1);' 3 6 9