Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses

Re: usage of "my" keyword

by taint (Chaplain)
on May 10, 2016 at 17:17 UTC ( [id://1162651] : note . print w/replies, xml ) Need Help??

in reply to usage of "my" keyword

OK. While at this point, it will seem quite obvious. I'm going to list it, for completeness. As I would have thought it the first thing to show up. :)

Here cant i declare a variabe without using my keyword.
Error: Global symbol "$i" requires explicit package name at line 6.
Technically, you can
use strict; use warnings; my $number=8; no strict; # could have also used "no strict vars" $i=0; #if i remove my keyword it gives error (not now) for($i=0;$i<20;$i++) use strict; # back to strict { print "present value of the number is:"; print $number++; print "\n"; }
OR, clobber them all up front:
use strict; no strict vars; use warnings; $number=8; # look MA, no MY! $i=0; #if i remove my keyword it gives error -- not NOW! for($i=0;$i<20;$i++) # here either { print "present value of the number is:"; print $number++; print "\n"; }
OK those were pretty much directly from the strictures documentation (which is why I felt they should have been included here). But why not illustrate another possibility -- global Variable Scoping in Perl: the basics?
#!/usr/bin/perl -w our ( $number, $i ); use strict; $number=8; # NOTE the absence of my $i=0; # AGAIN no my used here for($i=0;$i<20;$i++) # OR here { print "present value of the number is:"; print $number++; print "\n"; }
Cool, huh? Well, not really. While the PHP language practically encourages global variables. In most cases, it should be avoided. If for no other reason; security reasons. Ovid has written a nice overview, that outlines global variables scoping, titled: 'our' is not 'my', that better describes this.

There. Now this feels complete :)


λɐp ʇɑəɹ⅁ ɐ əʌɐɥ puɐ ʻꜱdləɥ ꜱᴉɥʇ ədoH