cshields36 has asked for the wisdom of the Perl Monks concerning the following question:

How can I find the location of each comma in a string. Like joe,is,at,home

Replies are listed 'Best First'.
Re: Find Comma in a string
by Tomte (Priest) on Jun 25, 2003 at 17:02 UTC

    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.

      ++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
Re: Find Comma in a string
by artist (Parson) on Jun 25, 2003 at 16:54 UTC
    Starting first character at '1'.
    $_ = q(joe,is,at,home,and,going,to,market,); while(/\,/g){ print pos()," "; }

    Answer:

    4 7 10 15 19 25 28 35
    
    artist
Re: Find Comma in a string
by thelenm (Vicar) on Jun 25, 2003 at 17:00 UTC
    Maybe something like this, which builds up an array of the offsets where a comma is found:
    $_ = "joe,is,at,home"; my @pos; push @pos, pos()-1 while /,/g; print "@pos\n";

    -- Mike

    --
    just,my${.02}

Re: Find Comma in a string
by waswas-fng (Curate) on Jun 25, 2003 at 18:19 UTC
    And just to be safe, why are you looking for the positions of the commas? Depending on what you are trying to do with that info there may be a better way to do it avaoiding this step.

    -Waswas
      What I really needs I have user credentials in a older system in jdoe,dept,comp and I need it in fully distiguisded to manipulate using ldap like cn=jdoe,ou=dept,o=comp.
        $input_string = "jdoe,dept,comp\n"; chomp $input_string; ($cn_temp, $ou_temp, $o_temp) = split /,/ , $input_string; print "cn=$cn_temp,ou=$ou_temp,o=$o_temp\n";
        will print "cn=jdoe,ou=dept,o=comp" -- Perl has many wonderful string tools, you dont have to do it like C. =)

        -Waswas