perlfan99 has asked for the wisdom of the Perl Monks concerning the following question:

i have two functions, only difference is the how parameter is assigned "my $data = @_ vs. my ($data) = @_" (for me, they are same), i don't know why test1 gives the correct result, but test2 doesn't, it always prints out the size of the parameters.

sub test1 { my ($data) = @_; print "test1 data = $data\n"; } sub test2 { my $data = @_; print "test2 data = $data\n"; } test1("hello"); test2("hello"); test2( qw(hello world) ); OUTPUT: test1 data = hello test2 data = 1 test2 data = 2

Replies are listed 'Best First'.
Re: function parameter assignment question
by GrandFather (Saint) on Jul 18, 2008 at 04:17 UTC

    my $data is scalar context so the count of elements in the array @_ is assigned to $data.

    my ($data) is list context so the first element of the array @_ is assigned to $data.

    See Context.


    Perl is environmentally friendly - it saves trees
Re: function parameter assignment question
by ikegami (Patriarch) on Jul 18, 2008 at 04:31 UTC
      very helpful, thanks!

        You really should consider doing something about this memory problem ;-)

Re: function parameter assignment question
by blazar (Canon) on Jul 19, 2008 at 19:08 UTC
    i have two functions, only difference is the how parameter is assigned "my $data = @_ vs. my ($data) = @_" (for me, they are same), i don't know why test1 gives the correct result, but test2 doesn't, it always prints out the size of the parameters.

    (additional emphasis by me.)

    I personally believe that (leaving aside the fact that you had asked the very same question less than one month ago - for which ikegami has had to point out the answer he gave back then) you should strongly refrain from analyzing Perl code in terms of what that may possibly seem to you in favour of what that Perl actually does all the time: here in particular, the "problem" has nothing to do with subs or parameter assignment but with a basic (and thus one you should get rapidly acquainted with) feature of the Perl programming language - dwimmy differentiation of behaviour based on context.

    C:\temp>perl -E "my @l=qw/foo bar baz/; my ($x)=@l; my $y=@l; say for +$x, $y" foo 3

    See? No sub at all! End of story: parens do matter.

    --
    If you can't understand the incipit, then please check the IPB Campaign.