CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
Search Posts SEARCH
Who's Online WHO'S
Log in LOG

Home: Perl Programming Help: Advanced:
Read, Add, Save..



Mar 29, 2002, 3:18 PM

Post #1 of 3 (3780 views)
Read, Add, Save.. Can't Post

I have a file named options.txt - pretty much a flat database. It looks very similar to this:

@opt_order=("1", "2", "3");
%options=("1"=>"one", "2"=>"two", "3"=>"three");
%one=("item 1"=>"value1", "item 2"=>"value2");
%two=("item 1"=>"value1", "item 2"=>"value2");
%three=("item 1"=>"value1", "item 2"=>"value2");

I want my script to open this file, then add on a value such as "4" to the @opt_order and %options - and save the file so it looks exactly above, except with the added elements.. Any suggestions at all is suggested.
Run Dos Run


Mar 29, 2002, 10:23 PM

Post #2 of 3 (3778 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.

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}}{$_}||(),
close FILE;

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:

$FILE::nitems = @FILE::opt_order;

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


Mar 31, 2002, 5:44 AM

Post #3 of 3 (3766 views)
Re: [cypher_MS] Read, Add, Save.. [In reply to] Can't Post

Hi Cypher,

Maybe you want to check AppConfig module, it's really nice when it comes to getopt::long and configuration files...



Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives