Perl regular expressions help

R

Rumpa

Hi,
I am trying to learn perl regular expressions.
I have:
my $store = q(
<store>
<book>
<title>abc</title>
<author>xyz</author>
</book>
<book>
<title>pqr</title>
<author>mno</author>
</book>
</store>);

I want to extract the titles only in a loop. How can I do this?
Thanks,
Rumpa
 
P

Paul Lalli

Rumpa said:
Hi,
I am trying to learn perl regular expressions.
I have:
my $store = q(
<store>
<book>
<title>abc</title>
<author>xyz</author>
</book>
<book>
<title>pqr</title>
<author>mno</author>
</book>
</store>);

I want to extract the titles only in a loop. How can I do this?

Regular expressions are *not* the right tool for parsing XML-like data.
Please search http://search.cpan.org for the many XML parsing tools.
If you insist on this as a learning excercise, it would be something
along the lines of:

while ($store =~ m{<title>(.*?)</title>}g) {
print "Title: $1\n";
}

For more information:
perldoc perlretut
perldoc perlre

Paul Lalli
 
A

A. Sinan Unur

Rumpa said:
I am trying to learn perl regular expressions.

But parsing XML is best done by using an XML parser.
I have:
my $store = q(
<store>
<book>
<title>abc</title>
<author>xyz</author>
</book>
<book>
<title>pqr</title>
<author>mno</author>
</book>
</store>);

I want to extract the titles only in a loop. How can I do this?

Use an XML parser. You can build on the following example:

#!/usr/bin/perl

use strict;
use warnings;

use XML::parser;

my $xml = <<XML
<store>
<book>
<title>abc</title>
<author>xyz</author>
</book>
<book>
<title>pqr</title>
<author>mno</author>
</book>
</store>
XML
;

my $in_title;

my $p = XML::parser->new(Style => 'Stream', Pkg => 'main');
$p->parse($xml);

sub StartTag {
my ($x, $el) = @_;
return unless $el eq 'title';
$in_title = 1;
}

sub Text {
my ($x) = @_;
print "$_\n" if $in_title;
}

sub EndTag {
my ($x, $el) = @_;
return unless $el eq 'title';
$in_title = 0;
}

__END__
 
T

Tad McClellan

I want to extract the titles only in a loop. How can I do this?


Use a module that understands XML for processing XML data.


---------------------------
#!/usr/bin/perl
use warnings;
use strict;
use XML::Simple;

my $store = q(
<store>
<book>
<title>abc</title>
<author>xyz</author>
</book>
<book>
<title>pqr</title>
<author>mno</author>
</book>
</store>);

my $content = XMLin $store;

foreach my $book ( @{ $content->{book} } ) { # perldoc perlreftut
print "Title is '$book->{title}'\n";
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,567
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top