0

i am learning perl, want to call a function, and pass 2 parameters to it, here is the code:

use strict;
use warnins;

sub test
{
 my ($item) = @_;
 print "$item\n";
}

test("hello world");

the result is : hello world

if i change the code to be like this:

my $item = @_;

then the result is: 1

what's the reason for the difference ? a little confused, i understand @_ is the parameter passed to function test when calling it, which is string "hello world", then why after assign @_ to $item, the result is 1, seems the length of the array @_, but ($item) is the parameter itself,

tonyibm
  • 581
  • 2
  • 8
  • 24
  • 1
    This answered by [Scalar vs List Assignment Operator](https://stackoverflow.com/a/54564429/589924) – ikegami Jul 06 '19 at 04:48

1 Answers1

2

There are two different assignment operators, the scalar assignment operator and the list assignment operator. If what's to the left of = is a list, hash, array, or slice, it is a list assignment. Otherwise, it is a scalar assignment.

A scalar assignment gives its right operand scalar context. In scalar context, an array evaluates to the number of elements in the array.

ysth
  • 96,171
  • 6
  • 121
  • 214
  • so $item is a scalar, but ($item) is a list ? – tonyibm Jul 06 '19 at 02:50
  • yes. though in general `()` just affect precedence and don't "make" a list, this is one of a couple places where they syntactically make there be a different operator – ysth Jul 06 '19 at 03:00