Quote:
Originally Posted by bharatbsharma
Hello
I can define all variables in tcl programming in a file for instance var.cfg
and source the same file in my tcl script such as
source var.cfg
Is this possible in perl too?
|
Well, YES and NO. The YES part is that you can get values of variable from an external file provided the variables are global/package ones.
The NO part is that you can't get value of lexical variable through 'require', but you can through 'eval'.
A better idiom is to import an anonymous hash:
Code:
sergei@amdam2:~/junk> cat -n hash_importer.pl
1 #!/usr/bin/perl -w
2
3 use strict;
4
5 my $x = 10;
6 my $hash_ref = require './hash_to_be_imported.prl';
7
8 warn "\$x=$x";
9
10 foreach my $key(keys %{$hash_ref})
11 {
12 warn "key/value: $key/$hash_ref->{$key}"
13 }
sergei@amdam2:~/junk> cat -n hash_to_be_imported.prl
1 {
2 foo => 1,
3 bar => 2
4 }
sergei@amdam2:~/junk> ./hash_importer.pl
$x=10 at ./hash_importer.pl line 8.
key/value: bar/2 at ./hash_importer.pl line 12.
key/value: foo/1 at ./hash_importer.pl line 12.
sergei@amdam2:~/junk>
If you want to delve deeper into the issue and understand how Perl uses lexical scoping to isolate things, replace contents of 'hash_to_be_imported.prl' file with these:
Code:
sergei@amdam2:~/junk> cat -n hash_to_be_imported_1.prl
1 my $x = 0;
2
3 warn "IMPORTED FILE: \$x=$x";
4
5 {
6 foo => $x++,
7 bar => $x++
8 }
9
sergei@amdam2:~/junk>
and look carefully at the behavior/value of $x in both files.
The point of my example is
complete separation of the data to be imported from the importer - this allows a lot of reuse of the data to be imported. Another point is that data to be imported can
not screw up the importer provided the importer is written using only lexical variables.