Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re^4: Unclear about 'our'

by ibm1620 (Hermit)
on Dec 27, 2022 at 22:44 UTC ( [id://11149152]=note: print w/replies, xml ) Need Help??


in reply to Re^3: Unclear about 'our'
in thread Unclear about 'our'

I believe I've got it.

In your package foo above, my inclination would be to declare 'my $bar;' at the top, before the first sub, and simply refer to it as '$bar', if there were no need for users in other packages to access it.

In retrospect, I think using getters and setters is probably better than exposing variables.

Thanks for your efforts to clear this up for me.

Replies are listed 'Best First'.
Re^5: Unclear about 'our'
by haukex (Archbishop) on Dec 28, 2022 at 15:28 UTC
    In retrospect, I think using getters and setters is probably better than exposing variables.

    That's one way to do it, but I would actually recommend against that and suggest two alternatives instead. The reason is that if you simply encapsulate a global in getters/setters, then it's still a global, meaning you have the issue that one piece of code using your module might affect a different piece of code using the same module without meaning to, and also, if you don't use a package variable (our), that means that you're taking away the ability of users to use local to try and mitigate that effect.

    So instead, my suggestions would be to just use an our variable, either that or make the module OO and make this variable a property of the object. That means that different pieces of code can change their settings on their objects without affecting each other at all.

      I agree with your suggestion to make the module OO -- which means it's time to bite the bullet and learn how to write OO Perl. :-) I know there are various CPAN modules that support it; do you have a recommendation?

        Perl OO, at its simplest, actually doesn't involve that much boilerplate so that IMHO it's worth it to learn that - see my example below as well as perlootut and perlmod (Update: and perlobj). But when I do use a module, I typically go for Moo.

        package Foo; use warnings; use strict; sub new { my ($class, $bar) = @_; my $self = { bar => $bar }; return bless $self, $class; } sub foo { my $self = shift; print "Bar=", $self->{bar}, "\n"; } 1;

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11149152]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (6)
As of 2024-04-23 10:23 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found