Scalar vs List Assignment Operator
Asked Answered
S

1

5

Please help me understand the following snippets:

  • my $count = @array;
  • my @copy = @array;
  • my ($first) = @array;
  • (my $copy = $str) =~ s/\\/\\\\/g;
  • my ($x) = f() or die;
  • my $count = () = f();
  • print($x = $y);
  • print(@x = @y);
Sloop answered 7/2, 2019 at 0:0 Comment(4)
could you add an explicit question? there isn't onePsychogenic
my ($first) = @arrayElegy
@ysth, Technically, there are 8 questions. But feel free to rewrite.Sloop
@mob, Of course! AddedSloop
S
7

[This answer is also found in table format here.]

The symbol = is compiled into one of two assignment operators:

  • A list assignment operator (aassign) is used if the left-hand side (LHS) of a = is some kind of aggregate.
  • A scalar assignment operator (sassign) is used otherwise.

The following are considered to be aggregates:

  • Any expression in parentheses (e.g. (...))
  • An array (e.g. @array)
  • An array slice (e.g. @array[...])
  • A hash (e.g. %hash)
  • A hash slice (e.g. @hash{...})
  • Any of the above preceded by my, our or local

There are two differences between the operators.

Context of Operands

The two operators differ in the context in which their operands are evaluated.

  • The scalar assignment evaluates both of its operands in scalar context.

      # @array evaluated in scalar context.
      my $count = @array;
    
  • The list assignment evaluates both of its operands in list context.

      # @array evaluated in list context.
      my @copy = @array;
    

      # @array evaluated in list context.
      my ($first) = @array;
    

Value(s) Returned

The two operators differ in what they return.

  • The scalar assignment ...

    • ... in scalar context evaluates to its LHS as an lvalue.

        # The s/// operates on $copy.
        (my $copy = $str) =~ s/\\/\\\\/g;
      
    • ... in list context evaluates to its LHS as an lvalue.

        # Prints $x.
        print($x = $y);
      
  • The list assignment ...

    • ... in scalar context evaluates to the number of scalars returned by its RHS.

        # Only dies if f() returns an empty list.
        # This does not die if f() returns a
        # false scalar like zero or undef.
        my ($x) = f() or die;
      

        # $counts gets the number of scalars returns by f().
        my $count = () = f();
      
    • ... in list context evaluates to the scalars returned by its LHS as lvalues.

        # Prints @x.
        print(@x = @y);
      
Sloop answered 7/2, 2019 at 0:0 Comment(2)
change to say just array or hash or array or hash slice, to be inclusive of the postderef syntaxPsychogenic
@ysth, Ah yes, those didn't exists when this was originally writtenSloop

© 2022 - 2024 — McMap. All rights reserved.