Nidis
Nidis

Reputation: 175

How to count the number of times a string (XML tag) occurs in a line?

Let's say my XML file has multiple <Timestamp> tags in a single line. I am reading the document line by line. How can I count how many of these tags are there in every line? I want something like:

foreach "<Timestamp>" in $line {
  print "FOund";
}

Any idea?

Upvotes: 1

Views: 241

Answers (3)

Axeman
Axeman

Reputation: 29854

It's XML, useXML::Twig:

my $twig = XML::Twig->new( twig_roots => { Timestamp => 1 });
$twig->parsefile( $xml_file_path );
my $timestamp_count = ( my @a = $twig->root->children( 'Timestamp' ));

Upvotes: 1

SimonD
SimonD

Reputation: 638

The 'redo' control statement restarts execution of the current statement block. You can use it to write something like:

foreach $line (<>)
{
  $tag = $line =~ m/(<.*>)/;
  push @tags, $tag;
  if( $tag ) redo;
}

Be warned, I haven't run this.

Hope that helps.

Upvotes: 0

Mat
Mat

Reputation: 206841

while ($line =~ /<Timestamp>/g) {
    print "Found\n";
}

should do the trick. The /g modifier is important there. See Using regular expressions in Perl in perlretut, it has a part on global matching.

Upvotes: 3

Related Questions