more useful options | |
PerlMonks |
comment on |
( [id://3333]=superdoc: print w/replies, xml ) | Need Help?? |
my is not something new in Perl 5.14. It was introduced in Perl 5.0 almost 18 years ago, and is generally the recommended way of declaring variables. When you don't use my then you should have a damned good reason not to. Perl traditionally allowed you to use variables without declaring them. The strict pragma (also introduced in Perl 5.0) can be employed to force the programmer to declare all their variables. Most Perl programmers use strict routinely. Perl 5.14 made the version declaration use v5.14 also automatically use strict mostly to save everyone some typing. You have read wrong. my is not for "creating private variables in a subroutine"... or at least it's not exclusively for that. Try this example, which doesn't even define any subs:
From this example, I hope you can see that lexical variables (those declared with my are not private to a sub; they are private to a lexical scope - that is, an area between curly braces. (Each whole Perl module/script is also a scope in itself.) Thus it's quite easy to declare a variable which can be seen outside a sub:
The $global variable above is not fully global. It is available throughout the file, but other files cannot see it. (Say, in a situation where one module is trying to read a variable in another module.) This is often what you want. Perl's true globals are package variables. These need to contain "::". For example:
Perl gives you a shortcut for package variables. If you're in package Foo::Bar, then you can use our $monkey to make $monkey act as an alias for $Foo::Bar::monkey.
perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'
In reply to Re: Use of "my" after Perl v5.14
by tobyink
|
|