tags:

views:

103

answers:

3

I'm developing a perl script.

This is my input string in a file new.txt:

<ID>1</ID>
<CLASS>One</CLASS>
<NAME>Saran</NAME>

This is my code which simply prints the three lines:

#!/usr/bin/perl 
open(FILEHANDLE1,"new.txt") or die "Can't Open: $!\n";
while($line=<FILEHANDLE1>)
{ 
print "$line";
}
close FILEHANDLE1;

I need it to display only the contents between the tag. The output should be:

1 One Saran

How should I retrive the data between tags? Is there any way by using regular expressions?

+2  A: 

What have you tried? What specific problems are you having?

It looks like you might want something like this:

#!/usr/bin/perl

use strict;
use warnings;

$_ = 'Data1 some text Data2';

if (/Data1(.*)Data2/) {
  print "$1\n";
}

But your question is so vague that it's hard to be sure.

davorg
+8  A: 

You cannot parse XML with regular expressions.

You should use an XML parser instead.

Jon Purdy
I can't really see anything there that tells us the OP is actually trying to read XML. You're absolutely right if they are but who knows.
Nic Gibson
I think it's better to post a psychic ninja answer that turns out to be correct than to post no answer when you could have been helpful.
Jon Purdy
Possibly true - I was hoping he or she might respond to davorg's request for further info before responding.
Nic Gibson
This should be a comment, not an answer.
Ether
@Ether - this should be cast in stone. Or Adamantium. And perma-attached on top of SO.com :)
DVK
@DVK: indeed. :)
Ether
+3  A: 

If your input file is really as you described, you can do something like :

#!/usr/bin/perl 

use warnings;
use strict;
open my $FILEHANDLE1, '<', "new.txt" 
     or die "Can't open file 'new.txt' for reading: $!";
while(my $line=<$FILEHANDLE1>) { 
    chomp $line;
    $line =~ s!^<(\w+)>(\w+)</\1>!$2 !;
    print $line;
}
print "\n";
close $FILEHANDLE1;

Always

use strict;

and

use warnings;

Use three args open and lexical handles.

M42