Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats the difference between ($test) = (@test); and $test = @test; in Perl?

Tags:

perl

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

With one bracket around the variable it acesses the first element of the array. I cant find any info on what the bracket around the array does.

like image 719
SaltedPork Avatar asked May 31 '16 10:05

SaltedPork


1 Answers

($test) = (@test); 

This assigns the values inside of @test to a list of variables that only contains $test. So $test will contain the first element of @test. That's called list context. You can also leave out the parenthesis around @test.

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

This is also very commonly used to assign the parameters of functions to variables. The following will assign the first three arguments to the function and ignore any other arguments that follow.

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

    # ...
}

You can also skip elements in the middle. This is also valid. The bar value will not get assigned here.

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

$test = @test;

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

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

You can read more about context in perldata.

like image 85
simbabque Avatar answered Nov 15 '22 06:11

simbabque