Hi,
On 6/27/13, lee <l...@yun.yagibdah.de> wrote:
> Shlomi Fish <shlo...@shlomifish.org> writes:
>
>> Hi Lee,
>>
>> On Wed, 26 Jun 2013 10:18:44 +0200
>> lee <l...@yun.yagibdah.de> wrote:
>>
>>> Hi,
>>>
>>> the following example doesn't compile:
>>>
>>>
>>> use strict;
>>> use warnings;
>>>
>>>
>>> sub test {
>>>     print $counter . "\n";
>>> }
>>>
>>>
>>> my $counter = 0;
>>> while($counter < 5) {
>>>     test();
>>>     $counter++;
>>> }
>>>
>>>
>>> It says "Global symbol "$counter" requires explicit package name ...".
>>> When I put the subroutine after the 'while' loop, it works just fine, so
>>> what's the problem?
>>
>> The subroutine does not see the lexical $counter variable because it was
>> declared after its scope.
>
> The subroutine is never called before $counter is declared, so it is
> always available to the subroutine.  There should be an error only for
> instances when the subroutine is called before $counter is declared.
>
>> For more information, see:
>>
>> * http://www.plover.com/FAQs/Namespaces.html
>
> Ok, so perl has a totally broken design with variables :(  What's the
I don't think so. I think you are not really getting perl and Perl.
How would you this in another language say C or C++?
> solution to this problem?
Below is one way of solving this problem:
<CODE>
use strict;
use warnings;

sub test {
     print shift(@_) . "\n";
 }


 my $counter = 0;
 while($counter < 5) {
     test($counter); # pass the variable
    $counter++;
 }
</CODE>

 You can write your test subroutine like this:
 <CODE>
 sub test{
    my $count = shift(@_);
    print $count,$/;
 }
</CODE>
I would of course not call the subroutine test, using a more
descriptive name would be better.
Hope this helps.

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to