Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Using Perl to open, edit, and save files. 2

Status
Not open for further replies.

sosuke

Programmer
Apr 5, 2005
3
US
Alright, so a couple of days ago I find out it is now my job to write a module for Webmin, in Perl, of which I have not written a single line of code.

My goal is opening a file, changing a value, and then saving the file back to the server. I know about the rights I need to issue to the file and how to open a file and how to save.

What I don't know is how to find my way around the opened file, how to change what I want, and pull out.
Here is one of several files I want to edit, not all of them are xml.
<?xml version="1.0" encoding="UTF-8"?>
<targets>
<target path="/foo/bar">
<configuration>
<size>512</size>
</configuration>
</target>
</targets>

How can I edit just those three characters "512"? The solution will hopefully be universal because I need to apply it over several different configuration files...
 
For XML files I can recommend you to use XML parsers. Have a look to the PerlModule XML::Simple.

For plain text files, you can read, write it using filehandles. Check the perl documentation "Filehandles".

Cheers

dmazzini
GSM System and Telecomm Consultant

 
maybe this will help you.

Code:
use warnings;
use strict;
use XML::Simple;

#-----------------------------------------------
# read xml-file
#-----------------------------------------------
open( IN , "<./test.xml" );
my ( @doc ) = <IN>;
close( IN );
my $xmlin = join( '',@doc );   # create string 

#----------------------------------------------
# transfer xml to perl-hash
#----------------------------------------------
my $xml = XML::Simple::XMLin( $xmlin, KeepRoot => 1, ForceArray => 1 );
$xml->{targets}->[0]->{target}->[0]->{configuration}->[0]->{size} = [ "test" ];  # change value

my $xmlout = XML::Simple::XMLout( $xml,
				  KeepRoot => 1,
				  XMLDecl => '<?xml version="1.0" encoding="UTF-8"?>'
				);
#---------------------------------------------
# display hash and xml-string
#---------------------------------------------
use Data::Dumper;
print Data::Dumper::Dumper( $xml );
print "Out:\n$xmlout\n";
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top