[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [MacPerl] Scoping question



At 11.36 -0400 1999.07.20, gibson wrote:
>   # if we pass to here, the XML file is fine.  now parse to create a
>   # list of subjects in the file.
>   $nSubjects = 0;
>
>   $p3 = new XML::Parser(Handlers => {Start => \&hStartCnt});
>   $p3->parsefile('PBG3:Desktop Folder:photo_sites:RussiaPhotos.xml');
>
>   # this sub will detect each unique subject attribute in
>   # the file and create a list of names.
>
>   sub hStartCnt
>    {
>      # code deleted to shorten e-mail; real function uses $nSubjects
>      # to count unique values of 'subject'
>   }
>
>   # provide some feedback:
>   if($nSubjects == 0) {die ('Found no subjects')};
>
>With my data file, it finds the correct 4 subject entries.  If, on the
>other hand, I move the initial declaration of $nSubjects to the line
>immediately preceding the subroutine definition:
>
>   # the file and create a list of names.
>   $nSubjects = 0;
>   sub hStartCnt
>   (etc.)
>
>the value of $nSubjects is _always_ zero at the my feedback line at the
>end of the script.

Exactly.

>Since in both cases $nSubjects is defined outside the block of the
>subroutine, it would seem that it should be treated as a global variable
>(this is my understanding after reading MPPE).  Why is this not true?

Not a global variable.  A lexical variable is not global.  Access to it is
limited to the lexical scope.  In this case, the lexical scope is the file
(or if all of this code is in a block, then the lexical scope if the whole
block).

But that is neither here nor there.  You are setting $nSubjects _after_
hStartCnt is called.  It will always be 0 because "$nSubjects = 0" is the
last line of code to execute before the "if($nSubject == 0)" line.

--
Chris Nandor          mailto:pudge@pobox.com         http://pudge.net/
%PGPKey = ('B76E72AD', [1024, '0824090B CE73CA10  1FF77F13 8180B6B6'])

===== Want to unsubscribe from this list?
===== Send mail with body "unsubscribe" to macperl-request@macperl.org