
mhx
Enthusiast
Mar 29, 2002, 10:23 PM
Post #2 of 3
(1995 views)
|
|
Re: [cypher_MS] Read, Add, Save..
[In reply to]
|
Can't Post
|
|
Are you sure that this is the format you need for your file? I'll come up with a solution that is not exactly what you want, but very close, and perhaps more flexible than you need. However, I think the format may not be the best choice. [perl] #!/usr/bin/perl use strict; use warnings; use Data::Dumper; my $file = 'options.txt'; load( $file ); { no warnings; push @FILE::opt_order, '4'; $FILE::options{'4'} = 'four'; %FILE::four = ( 'item 1' => 'value 1', 'item 2' => 'value 2' ); $FILE::nitems = @FILE::opt_order; } save( $file ); sub load { my $file = shift; { package FILE; do $file } } sub save { my $file = shift; open FILE, ">$file" or die "can't open $file: $!\n"; for my $s ( keys %FILE:: ) { print FILE map { s=$/(?!$)\s*= =sg; $_ } map Data::Dumper->Dump([$_],["*$s"]), map /SCALAR/?defined $$_?$$_:():$_, map *{%FILE::->{$s}}{$_}||(), qw(SCALAR ARRAY HASH) } close FILE; } [/perl] The above script can load arbitrary blocks of Perl variable declarations from a file and save them back to the same or another file. While the content will remain the same, the order of the declarations may change. In the block between the load and save calls, you can access all data from the file and manipulate them with all functions Perl has to offer. You can also bring new entries into life, e.g. $nitems: [perl] $FILE::nitems = @FILE::opt_order; [/perl] Even though this works, I still don't think it's a good way to do it. You should either rethink your format or come up with a really good reason to keep it. -- mhx
At last with an effort he spoke, and wondered to hear his own words, as if some other will was using his small voice. "I will take the Ring," he said, "though I do not know the way."-- Frodo
|