[ale] perl question

Geoffrey Myers lists at serioustechnology.com
Wed Jan 18 08:05:31 EST 2012


Jim Lynch wrote:
> 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.

But you understand that the original code defined $foo globally as well, 
it's something different with the foreach.  I'm going to play with this 
a bit more.

> 
> Jim.
> _______________________________________________
> Ale mailing list
> Ale at ale.org
> http://mail.ale.org/mailman/listinfo/ale
> See JOBS, ANNOUNCE and SCHOOLS lists at
> http://mail.ale.org/mailman/listinfo


-- 
Until later, Geoffrey

"I predict future happiness for America if they can prevent
the government from wasting the labors of the people under
the pretense of taking care of them."
- Thomas Jefferson


More information about the Ale mailing list