What is the difference between ($ test) = (@test); and $ test = @test; in perl?

($test) = (@test); $test = @test; 

With one bracket around the variable, it takes the first element of the array. I can not find information about what the bracket around the array does.

+6
source share
1 answer
 ($test) = (@test); 

This assigns values โ€‹โ€‹inside @test list of variables containing only $test . So $test will contain the first element of @test . This is called a list context. You can also leave parentheses around @test .

 my @test = ('a', 'b'); my ($test) = @test; # 'a' 

It is also very often used to assign function parameters to variables. The following will assign the first three arguments to the function and ignore any other arguments below.

 sub foo { my ($self, $foo, $bar) = @_; # ... } 

You can also skip items in the middle. This is also true. The value bar will not be assigned here.

 my @foo = qw(foo bar baz); (my $foo, undef, my $baz) = @foo; 

 $test = @test; 

This forces @test into a scalar context. Arrays in a scalar context return the number of elements, so $test will become an integer.

 my @test = ('a', 'b'); my $test = @test; # 2 

You can learn more about context in perldata .

+14
source

All Articles