Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re^4: Is this a bug in Perl scope?

by tobyink (Abbot)
on Jul 22, 2012 at 19:15 UTC ( #983079=note: print w/ replies, xml ) Need Help??


in reply to Re^3: Is this a bug in Perl scope?
in thread Is this a bug in Perl scope?

This syntax:

package foo { ... }

... only works in Perl 5.14 and above. In earlier versions of Perl, you'll need a semicolon before the block...

package foo; { ... }

Though it is in my experience more conventional to put the package declaration inside the block itself:

{ package foo; ... }

Update: as per AnomalousMonk's post below, this latter style has the added advantage that the package declaration itself is lexically scoped, so after perl parses the closing curly brace it puts you back into the main package. I knew that already really. ;-) The new Perl 5.14 syntax also does this, but the middle example does not.

perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'


Comment on Re^4: Is this a bug in Perl scope?
Select or Download Code
Re^5: Is this a bug in Perl scope?
by AnomalousMonk (Abbot) on Jul 22, 2012 at 22:59 UTC
    { package foo; ... }

    In addition, prior to 5.14 (and even post-5.14) this idiom terminated the scope of the enclosed package, which was (and is) very useful.

    >perl -wMstrict -le "{ package Foo; sub my_pkg { print 'works pre-5.14: ', __PACKAGE__; } } ;; package Bar { sub my_pkg { print 'post-5.14: ', __PACKAGE__; } } Foo::my_pkg(); Bar::my_pkg(); print __PACKAGE__; " works pre-5.14: Foo post-5.14: Bar main

    Update: Expanded code example.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (13)
As of 2014-09-23 17:38 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (234 votes), past polls