[ale] perl question

Jim Lynch ale_nospam at fayettedigital.com
Tue Jan 17 13:58:36 EST 2012


On 01/17/2012 12:47 PM, Geoffrey Myers wrote:
> Brian Mathis wrote:
>> On Tue, Jan 17, 2012 at 11:22 AM, Derek Atkins<warlord at mit.edu>  wrote:
>>> Geoffrey Myers<lists at serioustechnology.com>  writes:
>>>
>>>> Oh the loop works as defined, it's just that the value is not passed to
>>>> the sub bar()  My expectation was that since the call to bar() was
>>>> inside the loop, that $foo would be accessible within the sub.
>>> Alas, it doesn't work that way.  PERL doesn't scope variables that way.
>>> You would need to define a global and assign it, or you would need to
>>> pass it as a variable to the sub.
>>>
>>> -derek
>>
>> It doesn't, and shouldn't, work that way in /any/ programming
>> language.  The problem is definitely that the variables are never
>> passed to the sub, and trying to do it through bash-style globals is
>> very, very bad form (bash is not a programming language).
>>
>> The first thing you should be doing in all Perl programs is "use
>> strict;" before anything else.  That would have caught this error
>> right away.
> I should provide some background.  We ALWAYS:
>
> use strict;
> use warnings;
>
> In all our code.  I am making changes to someone else's code and came
> across this solution.  Although I agree, it's not the way to do it, I
> was trying to understand why it did not work.
>
> I'm trying to understand why that code does not work, but this does:
>
> #!/usr/bin/perl
>
> use strict;
> use warnings;
>
>
> my $foo = "stuff";
>
> bar();
>
> sub bar
> {
>       printf "%s\n", $foo;
> }
>
In this case, $foo is global, apparently (and I wasn't aware it worked 
that way) the $foo in the foreach block is local in the previous 
example.  I thought you had to declare it as my $foo for it to become a 
scoped local variable.  I was obviously wrong.

Jim.


More information about the Ale mailing list