in reply to Doubt in Eval
I'm not far above an initiate myself. But yes, declaring $a with my within the eval limits its scope only to that eval block -- as declaring anything with my makes it a lexical variable limited to whatever { } block it is within (not just eval; the same goes for a sub or 'for' or any block). If you want a global variable -- why do you want a global variable? If you just want something that's visible to both your eval and your sub, you could declare 'my $a' outside both blocks -- (creating a lexical variable at the package level). It would do what you need it to do, and make it effectively 'global' to your script here.
Does this sound confusing? Sorry. I am still figuring out scope myself. I read this excellent article on scope the other day (discovered in a link here). It is kind of old, but timeless (in recent versions of Perl, 'our' declarations are recommended over 'use vars' for package variables).
In any case, I would recommend the pragmata "use warnings 'all'" and "use strict" to help you catch issues like this. It's particular helpful when you're learning, but recommendable always.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Doubt in Eval
by AnomalousMonk (Archbishop) on Feb 17, 2012 at 05:17 UTC |