Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between my ($variableName) and my $variableName in Perl?

Tags:

What's the difference between my ($variableName) and my $variableName in Perl? What to the parentheses do?

like image 372
John Avatar asked Jan 24 '10 07:01

John


People also ask

What is the difference between my and our in Perl?

my is used for local variables, whereas our is used for global variables.

What is $_ called in Perl?

There is a strange scalar variable called $_ in Perl, which is the default variable, or in other words the topic. In Perl, several functions and operators use this variable as a default, in case no parameter is explicitly used. In general, I'd say you should NOT see $_ in real code.

What is my () in Perl?

my keyword in Perl declares the listed variable to be local to the enclosing block in which it is defined. The purpose of my is to define static scoping. This can be used to use the same variable name multiple times but with different values.

What are the different variables in Perl?

Perl has three main variable types: scalars, arrays, and hashes.


2 Answers

The important effect is when you initialize the variable at the same time that you declare it:

my ($a) = @b;   # assigns  $a = $b[0] my $a = @b;     # assigns  $a = scalar @b (length of @b) 

The other time it is important is when you declare multiple variables.

my ($a,$b,$c);  # correct, all variables are lexically scoped now my $a,$b,$c;    # $a is now lexically scoped, but $b and $c are not 

The last statement will give you an error if you use strict.

like image 183
mob Avatar answered Oct 20 '22 01:10

mob


The short answer is that parentheses force list context when used on the left side of an =.

Each of the other answers point out a specific case where this makes a difference. Really, you should read through perlfunc to get a better idea of how functions act differently when called in list context as opposed to scalar context.

like image 33
EmFi Avatar answered Oct 20 '22 00:10

EmFi