On 11/01/2011 03:02 PM, rent0n wrote:
Hi all,

Can somebody please explain what is the difference between:

sub subroutine {
my $var = @_;

that puts @_ in a scalar context which returns the number of elements in an array.
...
return 1;
}

and:

sub subroutine {
my ($var) = @_;
...

that puts @_ in a list context which returns its elements in a list. the first element is assigned to $var.

return 1;
}

I think it's something related to the context but I'm not completely
sure. What I know is that to have the behaviour I want I have to declare
the variable like in the second example (with parentheses).
This confuses me a bit because it's not the way I usually declare
variables in my main program (that is, without parentheses).

it is context as you surmised. the reason you see it differently has nothing to do with subs or @_. it is that you are likely declaring your file scoped variables without initializing them. it is the assignment that is making the difference and not the sub. if you did this outside a sub it would have the same problem as in the sub:

my $foo = @bar ;

so just always use parens around the my list when you assign @_ to them and you will be fine. it is the standard idiom for getting args inside a sub.


Please assume I'm 5 years old.

now go sit in the corner for 10 minutes or until you learned your lesson here! read more about context in perldata. :)

uri



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