Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation

Re: usage of "my" keyword

by taint (Chaplain)
on May 10, 2016 at 17:17 UTC ( #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

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (2)
As of 2022-05-28 19:53 GMT
Find Nodes?
    Voting Booth?
    Do you prefer to work remotely?

    Results (101 votes). Check out past polls.