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

I am having an issue using split to count instances of a pattern. I was told that I could use the code below to do it but the only output that I'm getting is "-1-1-1-1-1-1-1-1-1-1". I know it's something simple that I'm doing wrong but I just can't see it. If anyone has a suggestion, I would greatly appreciate it.

open (IN, "c:/work/XML_Count/14.xml") || die "Cannot open 14.xml"; while (<IN>){ chomp; my @t=split(/mapping id="/,$_); print $#tt; } close IN;

Replies are listed 'Best First'.
Re: Count Using Split
by Bloodnok (Vicar) on Sep 17, 2008 at 17:28 UTC
    Hi,

    There's a typo: methinx $#tt s/b $#t...

    HTH

    A user level that continues to overstate my experience :-))

      Thanks for the response. I caught that one right after I posted it but it still doesn't yield a useful count. It is giving me "0-100000-10145". I'm thinking that the 145 might be the count that I'm looking for but I'm not sure why the other digits are printing out. Is this a result of too much formatting in the xml file?

        Show us the line of the input xml file that is giving you this result.

        As an alternate approach, have you considered using one of the CPAN modules, such as XML::Twig? XML is notoriously difficult to parse.

Re: Count Using Split
by kyle (Abbot) on Sep 17, 2008 at 17:34 UTC

    As Bloodnok says, you've mistyped a variable name. I'd add that this error would have been caught immediately if you'd used strict. It's also a good idea to use warnings.

      Actually, I didn't paste all of my code. I just pasted the main part. I'm sorry if this caused any confusion.

Re: Count Using Split
by jwkrahn (Abbot) on Sep 17, 2008 at 17:36 UTC

     print $#tt; should probably be  print scalar @t; instead.

      No, because if one occurence of the search string is found, the string is split into two. So your code would print 2 when it should print 1. Since I don't like the $# syntax either, I would use print @t-1;
        No, because if one occurence of the search string is found, the string is split into two.

        Then  my @t=split(/mapping id="/,$_); should be  my @t = /mapping id="/g; instead.

            :-)