Sean Sugrue wrote:
>
> I am trying to create a hash that takes an xml input from a file retrieves
> all lines
> that has the word test_number in it, splits it to retrieve the actual test
> number and then
> when the hash is populated "while" through it and print out the keys and
> values. I don't really have a good grasp of how to create, populate and
> manipulate hashes so
> I'm running into problems. Anyone have a suggestion?
> Below is a sample of my code not yet finished and some
> of the text from the xml file.
>
> #!/usr/local/bin/perl
> $i=0;
>
> print" trying open a file \n";
> open(XML, "temp.xml") || die("Cannot open file \n");
> while(<XML>)
> {
> if($_=~/test_number/){
> @test_number=split/\<|>/,$_;
> $hash_try{$i}=$test_number[2];
> $i++;
> }
> }
> close(XML);
>
> while(($key,$value)=(%test)){
> print"$key=>$value \n";}
>
>
> XML file sample
>
>
> <begin_program_seg>
> <section_name>CONTINUITY_seq</section_name>
> </begin_program_seg>
>
> <functional_result>
> <test_number>1</test_number>
> <head_num>1</head_num>
> <site_num>0</site_num>
> <test_flags alarm='n' reliable_test='y' timeout='n' executed='y'
> aborted='n' passed='y' ></test_flags>
> <description><![CDATA[
> + dig opn/sht <> CONTINUITY_test
> ]]></description>
> <patt_gen_num>0</patt_gen_num>
> </functional_result>
>
> <functional_result>
> <test_number>2</test_number>
> <head_num>1</head_num>
> <site_num>0</site_num>
> <test_flags alarm='n' reliable_test='y' timeout='n' executed='y'
> aborted='n' passed='y' ></test_flags>
> <description><![CDATA[
> - dig opn/sht <> CONTINUITY_test
> ]]></description>
> <patt_gen_num>0</patt_gen_num>
> </functional_result>
use XML::Parser for this. using reg. exp for his works but isn't as
reliable. consider you have a line:
<whatever>test_number</whatever>
your reg. expression will catch it but this is probably not what you want.
now, you might change your reg. expression to include the '<>' but it's
mess as you go along. XML::Parser provides cleaner way:
#!/usr/bin/perl -w
use strict;
use XML::Parser;
my %hash;
my $test_number = 0;
my $string = '';
my $xml = new XML::Parser(Handlers =>
{Start => \&start, End => \&end, Char => \&string});
open(XML,'file.xml') || die $!;
$xml->parse(*XML);
close(XML);
while(my($i,$j) = each %hash){
print "key $i : value $j\n";
}
sub start{
$test_number = 1 if($_[1] =~ /^test_number$/i);
}
sub end{
if($_[1] =~ /^test_number$/i){
$hash{$string}++;
$string = '';
$test_number = 0;
}
}
sub string{
$string .= $_[1] if($test_number);
}
__END__
i think this's much more cleaner than using reg. exp.
david
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]