There are a couple of problems with your sub. You say it takes no parameters with sub counttags() and Perl will enforce that (if it notices at the right time). But you use $_[0] which accesses the first parameter.

You use $_ but don't give it a value anywhere.

The common wisdom is that parsing markup is hard and if it conforms to HTML or XML specifications you are much better to use one of the numerous modules designed for the purpose such as XML::Twig or HTML::TreeBuilder. All that aside, the following clean up of your code and expansion into a runable sample may be a good basis for rephrasing your actual question with some sample code to demonstrate your problem:

use strict; use warnings; my $str = '<start> </begin> </this> </that> <begin> </start>'; counttags ($str, 'begin'); sub counttags { my ($test, $target) = @_; my $stag = $test =~ /<$target>/g; my $etag = $test =~ /<\/$target>/g; if($stag != $etag) { print "Number of Start and End tags for element $target does n +ot match"; } }

Prints:

Number of Start and End tags for element begin does not match

DWIM is Perl's answer to Gödel

In reply to Re: Counting the start and end elements in a line by GrandFather
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.