On 5 May 2010 14:36, Harry Putnam <rea...@newsguy.com> wrote:
> "Uri Guttman" <u...@stemsystems.com> writes:
>
>>   HP> The output from the script below:
>>   HP> Shows 6 elements arrive in dispt($g, @ar) as @_.  But when sub N(@_)
>>   HP> is called, no variables arrive there. @_ is empty. When it seems like
>>   HP> 5 elements should have arrived there
>>
>> well, it helps if you actually pass in arguments. @_ is NOT a global.FF
>>
>>   HP>     my $code = $dispt{$selection} || $dispt{'error'} ;
>>   HP>     $code->();
>>
>> you aren't passing anything in to $code. you need to put something in
>> the () which then is set in the @_ of the called sub.
>
> As usual, I'm a little confused here.  First, what is a `global.FF'?

I don't see "FF" in uri's original post, your reader may have mangled
it. He said "@_ is NOT a global."

> And why would it matter that `...@_' is not global when its content was
> placed into a sub function?
>
> Inside dispt {...the sub function @_...} `...@_' is alive and well
>
>  (I'm changing the name of the hash `%dispt' (inside sub dispt {...})to
>  %hash, it was probably a poor choice of names)
>
> -------        ---------       ---=---       ---------      --------
> #!/blah/blah/perl
>
>  ## out here in global country �...@_' is unknown
>
>  dispt($var,@ar);
>
>  sub dispt { ...
>   ## @_ is alive here containing $var,@ar.
>
>   %hash = (  print N(@_ # `...@_' is dead here at the N(@_) call)
>  );
>
>  ...}
>
> which is also inside sub dispt {the sub function}.  Where does global
> come in?

The problem is in these lines:

sub dispt {
# snip
my %dispt = (
              N => sub { print  N(@_). "\n"; }, # THIS @_ HERE is the problem
# snip
 );
# snip
   my $code = $dispt{$selection} || $dispt{'error'} ;
   $code->(); # no arguments passed to &$code
}

The problem is that you have two nested subs. You have sub dispt {}
but you also have the anonymous sub { print N(@_)."\n"; }. @_ is the
argument list to the *innermost* sub. So @_ within that anonymous sub
is not the argument list to dispt (which is ($var, @ar) ) but the
argument list to the call to the anonymous sub, which happens in the
line $code->();. There is nothing between the parens, so you pass
nothing to the anonymous sub. Therefore, within that anonymous sub, @_
is an empty array.

Example with nested subs and arglists:

sub foo {
   print @_; # prints hello
   sub bar {
      print @_; # prints howdy. @_ is bar's arglist, not foo's
   }
   my $subref = sub {
      print @_; # prints awooga. @_ is the anonymous sub's arglist, not foo's
   };
   bar('howdy');
   $subref->('awooga');
}
foo('hello');


Phil

--
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