Can anyone tell me what is wrong in this?
quotemeta.

You're probably trying to use special metacharacters for regexes as normal matching characters. BTW you should limit the scope of those variables. And don't use sub prototypes!! (the parens)

You can do this:

sub counttags { my $stag=0; my $etag=0; my $tag = quotemeta($_[0]); while ($_ =~ /<$tag]>/g) {$stag++} while ($_ =~ /<\/$tag>/g) {$etag++} if($stag != $etag) { print "Number of Start and End tags for element $_[0] does not m +atch"; } }
And call you sub with quoted strings, not barewords.

But as a test, this isn't sufficient. You probably should check whether your tags are balanced, not tag soup. I think you'd best use a stack.

sub check_tags_balance { my @tagstack; while(/<(\/)?([^>]+)>/g) { unless($1) { # opening tag push @tagstack, $2; } else { # closing tag unless(@tagstack and $2 eq pop @tagstack) { print "Found an unbalanced closing tag $2\n"; return; } } } if(@tagstack) { print "Missing closing tags for @tagstack\n"; } else { print "Tags balanced.\n"; } } $_ = "I assume <b>everything</b> is <i><b>ok</b></i>"; check_tags_balance();

In reply to Re: Counting the start and end elements in a line by bart
in thread Counting the start and end elements in a line by rsriram

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.