Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW

Sharing variables

by Miguel (Friar)
on Feb 14, 2006 at 00:16 UTC ( #529973=perlquestion: print w/replies, xml ) Need Help??
Miguel has asked for the wisdom of the Perl Monks concerning the following question:

Esteemed Monks,

Since I don't see anyone (those authors that suggest good practices) sharing variables across modules this way, I wonder if I'm doing the right thing.

For example:
'test' is the main program;
'' declares and initializes some variables I'll use across the modules;
'' is a module.

File: test ------------------------------------------ #!/usr/bin/perl -Tw $|++; use strict; BEGIN { require "./"; } START: hello_world(); sub hello_world { print $::q->header, $::q->start_html, $::test->SayHelloTo({WHO=>"World!"}), $::q->end_html; } File: ------------------------------------------ #!/usr/bin/perl -Tw; use strict; use lib './'; use CGI; our $q = CGI->new; use test(); our $test = test->new; File: ------------------------------------------ package test; use strict; use vars qw($VERSION); $VERSION = 1.0; sub new { my $class = shift; $class = ref($class) || $class; my $self = {}; bless($self, $class); return $self; } sub SayHelloTo { my $self = shift; $self->{PARAMS} = shift if @_; my $params = $self->{PARAMS} || ''; return $::q->p("Hello", $params->{WHO}); } 1;
This code doesn't output any error or warning and it doesn't look slow - well, it's a short example anyway - so, my question is: is this a tremendous error? what is your advice?


Replies are listed 'Best First'.
Re: Sharing variables
by chromatic (Archbishop) on Feb 14, 2006 at 00:55 UTC

    It's not awful for small programs, but it's not great. The $::scalar_name syntax only works if you define a package global in the main package. Sometimes that's useful, but I try to group code that needs to access certain objects and data structures all together in the same or related modules and classes.

    This is starting to sound pretty vague, but my rule is "This isn't bad for short programs, but there are better ways to organize larger programs."

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://529973]
Approved by spiritway
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (3)
As of 2018-03-24 16:29 GMT
Find Nodes?
    Voting Booth?
    When I think of a mole I think of:

    Results (299 votes). Check out past polls.