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.

Shared variable module

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;

Recieving module: Foo

package Foo; use SharedVariables; sub Print { print "Foo Scalar1 $scalar1\n"; } sub Set { $scalar1 = 'Foo'; print "Set Foo\n"; } 1;

Recieving Module: Bar

package Bar; use SharedVariables qw(:scalars); sub Print { print "Bar Scalar1 $scalar1\n"; } sub Set { $scalar1 = 'Bar'; print "Set Bar\n"; } 1;

Main program

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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.