SaltedPork
SaltedPork

Reputation: 377

Whats the difference between ($test) = (@test); and $test = @test; in 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.

Upvotes: 6

Views: 204

Answers (1)

simbabque
simbabque

Reputation: 54323

($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.

Upvotes: 14

Related Questions