in reply to Re: Saving application configuration to files
in thread Saving application configuration to files

I like the idea of using 'do', but I have what's probably a basic mis-understanding on my part.

Under use strict;, the 'do' executes what's in my configuration file, but I don't understand what happens to my scope. When I'm back in the calling file, I can't see the variable set in the config file. I tried 'package main;' at the top of my config, and it didn't do the trick.

######### calling script #!/usr/bin/perl use strict; my $x; my $file = 'my.conf'; unless (my $return = do $file) { warn "couldn't parse $file: $@" if $@; warn "couldn't do $file: $!" unless defined $return; warn "couldn't run $file" unless $return; } print "\$x is $x\n"; ########## config script (my.conf) package main; $x = 'abcdef'; 42;

Where am I going wrong here?

Replies are listed 'Best First'.
Re: Re: Re: Saving application configuration to files
by maa (Pilgrim) on Mar 31, 2004 at 06:25 UTC

    It works if you declare your variables using our.

    I've never actually used this method though... see perldoc -f our for info on how it affects scope.

    You can ensure you don't go clobbering things by reassigning the imported values once you get them (if you feel safer)

    #!/usr/bin/perl use strict; our ($x); my $file = 'conf.pl'; unless (my $return = do $file) { warn "couldn't parse $file: $@" if $@; warn "couldn't do $file: $!" unless defined $return; warn "couldn't run $file" unless $return; } print "\$x is $x\n"; my $var_x=$x; ########## config script (my.conf) $x = 'abcdef';

    I suppose the method you are going to use depends on who is going to be editing the config file, doesn't it... if they know perl then any method should be fine. If they don't then a standard INI format or plain assignments might be better.

    HTH - mark