Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare multiple variables on one line in perl

Tags:

I found that I can declare two variables in one statement using:

my ($a,$b)=(1,2); 

But I think this syntax may be confusing, for instance, if we had five variables declarations, it would be difficult to see which value belongs to which variable. So I think it would be better if we could use this syntax:

my $a=1, $b=2; 

I wonder, why is this kind of declaration not possible in Perl? And are there any alternatives?

(I am trying to avoid repeating my for each declaration like: my $a=1; my $b=2;)

like image 477
Håkon Hægland Avatar asked Apr 12 '14 14:04

Håkon Hægland


People also ask

Can you declare multiple variables in one line?

Every declaration should be for a single variable, on its own line, with an explanatory comment about the role of the variable. Declaring multiple variables in a single declaration can cause confusion regarding the types of the variables and their initial values.

How do I declare a variable in Perl?

Perl variables do not have to be explicitly declared to reserve memory space. The declaration happens automatically when you assign a value to a variable. The equal sign (=) is used to assign values to variables.

What does $@ mean in Perl?

In these cases the value of $@ is the compile error, or the argument to die.


1 Answers

No. Variables declared by my are only named once the next statement begins. The only way you can assign to the newly created variable is if you assign to the variable it returns. Think of my as new that also declares.

As for your particular code,

my $a=1, $b=2; 

means

((my $a)=1), ($b=2); 

Obviously, no good.

If you had used variables that weren't already declared[1], you would have gotten a strict error.


  1. $a and $b are predeclared in every namespace to facilitate the use of sort.
like image 107
ikegami Avatar answered Oct 09 '22 10:10

ikegami