in reply to Programmatic access of hashes
#!/usr/bin/perl package XMLcrude; use strict; use warnings; sub new{ my $this = shift; my $class = ref($this) || $this; my $self={@_}; bless $self, $class; return $self; } # If you do not have access to XML::Simple, and are not allowed to ins +tall it, this can replace it in most situations. ############################# # XML IN - suck in the XML file # sub XMLin{ my $self=shift; $self->{file}=shift||return; #load file into @file open my $FILE, '<', $self->{file} or die "Unable to open log file [$se +lf->{file}], system said $!"; if(<$FILE> !~ /<?xml/){die 'Not an XML file! Header "<?xml" is missin +g!'} my @file=<$FILE>; close $FILE; my $data=join '',@file; $data=~s/<!--.*?-->//gs; # Strip out comments. my ($root,$value,@key); foreach my $tag(split(/(<.*?>)/,$data)){ #found a tag, so create a hash element for it. if($tag=~/<((?:[^>'"]*|(['"]).*?\1)*)>/){ #start tag - add element depth if($tag!~/^<\//){ $tag=~s/<|>//g; # Remove brackets push @key,$tag; # <START> Starting + tag, so remember this tag name. Used to make key for hash element. #end tag - remove element depth }else{ if(defined $value){ #record data my $key=\$self; # Get reference to our +self. (A reference to the reference to the hash that stores our data) $key=\($$key->{$_}) for @key; # Build up hash eleme +nt key using the tags we gathered in @key $value=~s/\n|\t//g; # Clean up the valu +e. if(length $value){$$key= $value;} # Assign value, i +ncluding zeros, to hash element reference if there is data $value=''; # Clear value for ne +xt round. } $root=pop @key; # </END> Closing ta +g, so lower the element depth... also, remember the very last value r +emoved. } next; # We are done process +ing tags. } $value.=$tag; # Record value } return $self->$root}; # XML document should + start with a "root" container element that holds everything. } 1;
|
|---|