Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: Unclear about 'our'

by LanX (Saint)
on Dec 27, 2022 at 18:11 UTC ( [id://11149140]=note: print w/replies, xml ) Need Help??


in reply to Unclear about 'our'

> Is this even what our is meant for?

to expand on HaukeX's explanantion:

our is meant (was introduced) to be analogue to my in declaring a "simple" var/symbol, but this time a package variable of the current package, not one private to the scope.

Both are lexically scoped ° and with "simple" I mean not fully qualified, hence $name vs $Package::name

strict -ness requires variables to be declared or fully qualified.

before our was introduced, the only way to use a simple package var with strict was the vars pragma, which led to messy scopes.

use strict; use warnings; { our $name = 42; # alias to $main::name my $ref_name = \$main::name; # ref to $main::name warn "$main::name - $name - $$ref_name"; package OTHER; # --- still same scope warn "$main::name - $name - $$ref_name"; $name = 666; # w/o strict this would be $OT +HER::name warn "$main::name - $name - $$ref_name"; } # out of scope warn "$main::name"; # --- compiletime error! # warn "$name - $$ref_name"; # Variable "$name" is not imported at c:/tmp/pm/our_vs_my.pl line 22. # Global symbol "$name" requires explicit package name (did you forge +t to declare "my $name"?) at c:/tmp/pm/our_vs_my.pl line 22. # Global symbol "$ref_name" requires explicit package name (did you f +orget to declare "my $ref_name"?) at c:/tmp/pm/our_vs_my.pl line 22. our $name; # rebind alias for following s +cope warn $name;

42 - 42 - 42 at c:/tmp/pm/our_vs_my.pl line 9. 42 - 42 - 42 at c:/tmp/pm/our_vs_my.pl line 14. 666 - 666 - 666 at c:/tmp/pm/our_vs_my.pl line 18. 666 at c:/tmp/pm/our_vs_my.pl line 22. 666 at c:/tmp/pm/our_vs_my.pl line 32.

one difference to my is that our vars are not destroyed at the end of scope, the alias is just released.

Cheers Rolf
(addicted to the 𐍀𐌴𐍂𐌻 Programming Language :)
Wikisyntax for the Monastery

°) basically: available till the end of the surrounding block

UPDATE

expanded examples

Update

for a better understanding: Perl4 didn't have strict or my resp. private variables. Every simple var automatically belonged to the current package and one often needed local for dynamic scoping at run time. our filled the conceptual hole to have compile-time checking for package vars in a more stringent way than use vars could provide.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (1)
As of 2024-04-25 04:29 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found