in reply to Using variables, arrays etc from a perl module in main script.

You need to use our rather than my in the Perl module.

my:
our:

Notice above I use the scope operator. With our the scope operator is not needed. The name of variable $bar in package Foo is $Foo::bar; however, when we declare $bar with our (i.e., our $bar; ), then to access $bar outside of package Foo we do not need the scope (i.e., $Foo::bar becomes just $bar).


abc.pl
#!/usr/bin/perl use strict; use warnings; use xyz qw(:DEFAULT @array); print "@array\n"; sub1("Hello!");
xyz.pm
package xyz; use strict; use warnings; require 5.008; require Exporter; our @ISA = qw(Exporter); our @EXPORT = qw(sub1); our @EXPORT_OK = qw(@array); open my $fh, '<', "qwerty.txt" or die "Cannot open file: ($!)"; our @array = <$fh>; sub sub1 { my $text = shift; print "Text: $text\n"; }

Replies are listed 'Best First'.
Re^2: Using variables, arrays etc from a perl module in main script.
by kennethk (Abbot) on May 12, 2010 at 19:17 UTC
    Notice above I use the scope operator. With our the scope operator is not needed. The name of variable $bar in package Foo is $Foo::bar; however, when we declare $bar with our (i.e., our $bar; ), then to access $bar outside of package Foo we do not need the scope (i.e., $Foo::bar becomes just $bar).

    While it may simply be a language issue, the above sounds incorrect to me. While our does make @xyz::array globally accessible, it is only accessible using a fully qualified package name (@xyz::array) outside its package (xyz) unless it is exported/imported. I am uncertain what you mean by the "scope operator" - do you mean the package name with double colon?

      Sorry, let me clarify... I say scope operator for "::" because I am used to C++ terminology.

      You are correct, I should have stated that when importing variables our allows us to leave out the fully qualified package name and just use the bare $foo. However, if not importing the var we need to use FQPN (e.g., $Package::var).

      Correct me if I am wrong, but before Perl 5.6 when we used "use vars", didn't we have to use FQPN even when importing the variable? It's been a long time, but it seems that was the case.
        vars created true globals that were exported into the default package, and did not require FQPNs. our's mechanism simply makes them visible (public) but does not export them into the default package. Thus, variables declared with our are accessible but won't clobber or be clobbered unless the import mechanism is invoked.
        hi i have one question in this... is their any way by which we can link/access the varibles value of other modules without defining it as global variables...?? Thanks in advance... :-)