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

Does anyone know a quick way to find out how many delimeters there are in any given record? I could be very dull and just substr the record and keep a count but I thought I'd read a shortcut somewhere - which I now can't find. It may have been using index but I'm not sure. Using a scalar with split nearly works but this returns the actual number of fields not delimeters.

Replies are listed 'Best First'.
Re: Delimeter Count?
by marto (Cardinal) on Nov 28, 2005 at 14:55 UTC
    Hi Ronnie,

    Try using tr:
    $string="firstname,surname,age,height,shoesize"; $count = ($string =~ tr/,//); print "There are $count delimeters in the string";
    hope this helps.

    Martin
Re: Delimeter Count?
by Fletch (Bishop) on Nov 28, 2005 at 14:55 UTC

    Call me crazy, but I'd bet there's some sort of simple relationship between the number of fields and the number of delimiters between them. But then you might have to use that newfangled "Math" stuff . . .

      The problem with the scalar option and split is that the number of fields is returned not the number of delimeters. The delimeter I was testing for was a pipe (|). Some of my records end with |||||| and some end with |fred|blogs. This produces a different result even if there are the same number of pipes.

        Use -1 as the third argument of split:

        $rec = 'has|trailing|pipes|||'; print(scalar(split(/\|/, $rec )), "\n"); # 3 print(scalar(split(/\|/, $rec, -1)), "\n"); # 6

        Consult perldoc -f split, specifically the discussion of using a negative number as LIMIT.

Re: Delimeter Count?
by Perl Mouse (Chaplain) on Nov 28, 2005 at 15:14 UTC
    I'd use any of split, tr///, or m//g depending on the details of the problem.

    But all solutions are fairly trivial.

    Perl --((8:>*