in reply to Re^2: wantarray - surprise behaviour
in thread wantarray - surprise behaviour

Does that mean the context where the wantarray is, or where the function call is?

Where the function call is.

If it's where the function is called as a hash value

blah() is not called "as a hash value". It is called while building a list (which eventually will be assigned to a hash.) For example:

%hash = (a => 'b', 'c', d => split(//, 'ef'));

results in

$hash{'a'} = 'b' $hash{'c'} = 'd' $hash{'e'} = 'f'

It's useful to think of the () as an operator creating an anonymous list.

couldn't you're example just as easily be (1, $a), instead of (1, @a)?

Yes, a scalar can be be provided when an a list is expected. However, I used @a because an array behaves differently in scalar and list contexts. (It returns the number of elements in the former, and the list of elements in the latter.)

Replies are listed 'Best First'.
Re^4: wantarray - surprise behaviour
by diotalevi (Canon) on Aug 31, 2004 at 22:25 UTC
    It's useful to think of the () as an operator creating an anonymous list.

    No it isn't. () is just about getting things to parse correctly. The list comes from the comma operators , and =>.

      I've seen this said before, but

      P:\test>perl -MO=Deparse -e"@a = 1,2,3,4,5; print @a" @a = 1, '???', '???', '???', '???'; print @a; -e syntax OK P:\test>perl -e"@a = 1,2,3,4,5; print @a" 1 P:\test>perl -MO=Deparse -e"@a = (1,2,3,4,5); print @a" @a = (1, 2, 3, 4, 5); print @a; -e syntax OK P:\test>perl -e"@a = (1,2,3,4,5); print @a" 12345

      Empirically, that suggests that the parens are, at least in some cases, required to build a list.


      Examine what is said, not who speaks.
      "Efficiency is intelligent laziness." -David Dunham
      "Think for yourself!" - Abigail
      "Memory, processor, disk in that order on the hardware side. Algorithm, algorithm, algorithm on the code side." - tachyon
        But they don't create lists. They are 'required' just as they are in some cases required to call a function correctly. That doesn't mean parens call functions. In the case you describe, parentheses are used for precedence:
        perl -MO=Deparse,-p -e"@a = 1,2,3,4,5; print @a" ((@a = 1), '???', '???', '???', '???'); print(@a); -e syntax OK
        A list is still created - it's just not the list you want.
      No, the list *doesn't* come from the comma. It comes from the assignment:
      sub foo { $c = wantarray; print $c ? "A" : defined $c ? "S" : "V" } (foo(), foo(), foo()); print "\n"; $v = (foo(), foo(), foo()); print "\n"; @v = (foo(), foo(), foo()); print "\n"; __END__ VVV VVS AAA

        Well, no. That's a case of a list in scalar or list context. I quote from perlop about the assignment operator.

        a list assignment in list context produces the list of lvalues assigned to, and a list assignment in scalar context returns the number of elements produced by the expression on the right hand side of the assignment.