Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re^4: scope of variable

by hdb (Monsignor)
on May 27, 2013 at 12:40 UTC ( [id://1035403]=note: print w/replies, xml ) Need Help??


in reply to Re^3: scope of variable
in thread scope of variable

bart's comment on closures is exactly the reason for your problem. See this simplified example:

use strict; use warnings; sub func { my $calls = shift; my $strange = "Call $calls"; print "In func (start): $strange\n"; sub subfunc1 { print "In subfunc1: $strange\n"; $strange .= " even"; } sub subfunc2 { print "In subfunc2: $strange\n"; } subfunc1(); subfunc2(); print "In func (end): $strange\n"; } func(1); func(2); func(3); func(4);

which creates the following output (including a couple of warnings!):

Variable "$strange" will not stay shared at closure2.pl line 10. Variable "$strange" will not stay shared at closure2.pl line 15. In func (start): Call 1 In subfunc1: Call 1 In subfunc2: Call 1 even In func (end): Call 1 even In func (start): Call 2 In subfunc1: Call 1 even In subfunc2: Call 1 even even In func (end): Call 2 In func (start): Call 3 In subfunc1: Call 1 even even In subfunc2: Call 1 even even even In func (end): Call 3 In func (start): Call 4 In subfunc1: Call 1 even even even In subfunc2: Call 1 even even even even In func (end): Call 4

which clearly demonstrates that the variable $strange in the subfuncs is decoupled from $strange in func in the second and subsequent calls to func. The warnings also tell the same story.

UPDATE: Compare to the following:

use strict; use warnings; my $strange; sub subfunc1 { print "In subfunc1: $strange\n"; $strange .= " even"; } sub subfunc2 { print "In subfunc2: $strange\n"; } sub func { my $calls = shift; $strange = "Call $calls"; print "In func (start): $strange\n"; subfunc1(); subfunc2(); print "In func (end): $strange\n"; } func(1); func(2); func(3); func(4);

whose output is probably what you expected. Whether or not this is good style is a diffent question ...

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others imbibing at the Monastery: (4)
As of 2024-04-19 02:03 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found