Search code examples
arraysperlscalar

Perl structures and assignment


In perldata, I found the following examples and explanations.

@foo = ('cc', '-E', $bar);

assigns the entire list value to array @foo, but

$foo = ('cc', '-E', $bar);

assigns the value of variable $bar to the scalar variable $foo. 

This really confuses me, so $foo is equivalent to $bar? How to understand the difference between @foo and $foo


Solution

  • The examples in perldata:

    @foo = ('cc', '-E', $bar);
    $foo = ('cc', '-E', $bar);
    

    Because @foo creates a list context, all the values in the parens are assigned to @foo. $foo on the other hand is a scalar, and so is only assigned the last element in the list, because it is in scalar context.

    It is equal to saying:

    'cc', '-E';
    $foo = $bar;
    

    In Perl, a scalar, like $foo, can only hold a single value, and so the rest of the list is simply discarded. An array, like @foo will slurp as many values as the list holds.

    In Perl, it is allowed to have the same name on variables of different types. @foo and $foo will be considered two different variables.