Its best to avoid global data and mixing namespaces. But, if you must share your variables like this use Perl's Exporter facility, rather than hand coding your own system.
I've included code that shows how to share a scalar, but an array or hash would work identically. I also didn't use strict, which all production code should do. Nothing I did here will fail under strictures.
package SharedVariables; use base Exporter; # Default export @EXPORT = qw( $scalar1 $scalar2 @array1 ); # Possible to export these @EXPORT_OK = qw( $scalar1 $scalar2 @array1 @array2 ); # Named groups to export %EXPORT_TAGS = ( scalars => [ qw( $scalar1 $scalar2 ) ], arrays => [ qw( @array1 @array2 ) ], ); 1;
package Foo; use SharedVariables; sub Print { print "Foo Scalar1 $scalar1\n"; } sub Set { $scalar1 = 'Foo'; print "Set Foo\n"; } 1;
package Bar; use SharedVariables qw(:scalars); sub Print { print "Bar Scalar1 $scalar1\n"; } sub Set { $scalar1 = 'Bar'; print "Set Bar\n"; } 1;
use SharedVariables qw(:DEFAULT); use Foo; use Bar; $scalar1 = 'Initialized'; print "Main Scalar1 $scalar1\n"; Foo::Print; Foo::Set; Foo::Print; Bar::Print; Bar::Set; Bar::Print; $scalar1 = 'Main'; Foo::Print; Bar::Print; __END__ C:\temp> test.pl Main Scalar1 Initialized Foo Scalar1 Initialized Set Foo Foo Scalar1 Foo Bar Scalar1 Foo Set Bar Bar Scalar1 Bar Foo Scalar1 Main Bar Scalar1 Main
TGI says moo
In reply to Re: Suggest me some code to share an array among packages???
by TGI
in thread Suggest me some code to share an array among packages???
by sanjay nayak
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |