http://www.perlmonks.org?node_id=1222429


in reply to Tk save variables into a file and load

Hi, I don't know about your code problem, but as to your original question:
I need help in perl Tk to save, load, default or change config variables, whenever i require. How do I approach.

One good way is to use Storable. It allows you to write an existing hash to a file, OR read the file back into a hash.

Here is some code showing it's basic use. For further info see ztkdb where I use this technique.

use Tk; use Storable; # Say your config information is in notebook.db # and your config hash is %info. # At startup check if notebook.db exists and load it # into your config hash. If it dosn't exist then it means it's the # first run of the program and do something to make the notebook.db my %info; # global hash to hold your data if(-e 'notebook.db'){ %info = %{retrieve('notebook.db')}; # direct to hash }else{ make_notebook() } # now in your program, as you change things and want to # store them to the notebook.db, you need to save it. # Here is a list of Tk related statements that will automatically # save your notebook.db whenever you exit the program #setup auto save of storable db $mw->protocol('WM_DELETE_WINDOW' => sub { &save_it() }); $SIG{__DIE__} = sub { &save_it()}; $SIG{INT} = sub { &save_it()}; $mw->bind('<Control-c>', [sub{&save_it(); Tk::exit;}] ); # and the save_it sub sub save_it{ store(\%info,'notebook.db'); print "saved\n"; }

I'm not really a human, but I play one on earth. ..... an animated JAPH